T-SQL Group with with where子句

时间:2013-02-12 15:09:07

标签: sql sql-server tsql group-by where-clause

 Masterid    CC  CLA DES NLCLA   NLDES
 -------------------------------------
 53006141    CN  0   0   1       1
 53006141    US  1   1   1       1
 53006141    UK  1   1   0       0
 53006142    US  1   1   0       0
 53006142    UK  1   1   0       0
 53006143    CN  0   0   1       1
 53006143    US  1   1   0       0
 53006143    UK  1   1   0       0

从上面的数据中我需要制作

  • MasterIds列表CC = USCC = CN以及NLCLA = 1NLDES = 1

输出应为

53006141
53006143

在MasterID下必须有CN和US。

有人可以帮我在SQL中执行此操作吗?

2 个答案:

答案 0 :(得分:9)

您可以通过添加WHERE子句来执行此操作,该子句将返回包含USCN的行:

select distinct Masterid
from yourtable
where cc in ('US', 'CN')
  and NLCLA = 1
  AND NLDES = 1

请参阅SQL Fiddle with Demo

如果您希望结果同时包含CNUS,那么您可以使用:

select Masterid
from yourtable
where cc in ('US', 'CN')
  and NLCLA = 1
  AND NLDES = 1
group by masterid
having count(distinct cc) = 2

SQL Fiddle with Demo

另一种方法是使用EXISTS获取同时包含USCN的MasterIds列表。然后将其他过滤器放在WHERE子句中,而不是子查询中。

select distinct masterid
from yourtable t1
where exists (select Masterid
              from yourtable t2
              where cc in ('US', 'CN')
                and t1.masterid = t2.masterid
              group by masterid
              having count(distinct cc) = 2)
  and NLCLA = 1
  and NLDES = 1;

请参阅SQL Fiddle with Demo

答案 1 :(得分:1)

一种方法是使用CTE

WITH CTE AS
(
    SELECT Masterid,CC,CLA,DES,NLCLA,NLDES,
        RN = ROW_NUMBER() OVER (PARTITION BY Masterid ORDER BY Masterid)
    FROM dbo.Table
    WHERE   CC IN('US', 'CN')
    AND     NLCLA = 1
    AND     NLDES = 1
)
SELECT Masterid FROM CTE WHERE RN = 1

Demo(感谢bluefeet提供的小提琴数据)

请注意,如果您想获取特定行,ROW_NUMBER分区函数会很有用,例如始终是每个Masterid的最新记录。但是,由于您还没有提供datetime列,我只是Masterid任意订购。