【发布时间】:2014-08-12 14:46:34
【问题描述】:
我使用的是 sql server 2012。我有两个表,M_SALES 和 M_SALES_COUNTRY。 M_SALES 包含一个名为 sale_id 的主键。 M_SALES_COUNTRY 还包含一个名为 sale_id 的字段,它是它的外键。 M_SALES_COUNTRY 还包含一个名为 country_code 的字段,该字段可以为空。
所以 M_SALES 包含一个唯一的 sale_id。 M_SALES_COUNTRY 可以包含多个相同的 sale_id。
对于来自 M_SALES_COUNTRY 的 1 条记录(可能有多个,但我只想要一个)的查询,为 M_SALES 表中的每个 sales_id 返回,这很好,也是我想要的。但是我想知道是否可以添加更多条件。
如果 M_SALES 中的 sale_id 引用 M_SALES_COUNTRY 中的多个 sale_id,我希望它返回 country_code 字段不为空的记录。如果所有记录 country_code 为 null,则返回 null。请看下面两个简单的例子。
sale_id country_code
AAA5555 null
AAA5555 null
AAA5555 D56
我要返回的记录是 D56。
下一个例子
sale_id country_code
AAA5555 null
AAA5555 null
AAA5555 null
只要返回一条记录,任何记录都可以在这里使用。
查询
select M_SALES.*, M_SALES_COUNTRY.*
from M_SALES cross apply
(
select top 1 M_SALES_COUNTRY.*
from M_SALES_COUNTRY
where M_SALES.sale_id = M_SALES_COUNTRY.sale_id
) MA_DEALS_COUNTRY
order by M_SALES.sale_id
【问题讨论】:
标签: sql sql-server