2013-02-12 50 views
1
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 

從上述數據我需要產生T-SQL組通過用where子句

  • MasterIds其中存在CC = USCC = CNNLCLA = 1NLDES = 1

的列表輸出應該是

53006141 
53006143 

在MasterID下必須同時存在CN和US。

有人可以幫我在SQL中做到這一點嗎?

回答

7

您可以通過添加一個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來獲取MasterIds列表,同時使用USCN。然後,您將其他篩選器放在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

+0

如果還有另外一行怎麼辦
53006144 CN 0 0 0 0 – LeBlues 2013-02-12 15:15:34

+0

@LeBlues如果有另一行,你的意思是什麼?在這種情況下除了結果之外,你會做什麼?它會返回相同的結果 - http://sqlfiddle.com/#!3/968a1/1 – Taryn 2013-02-12 15:16:14

+0

@LeBlues如果該行存在,那麼它符合'WHERE'的標準,所以它也將返回該行 – Lamak 2013-02-12 15:17:25

0

一種方法是使用一個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分區功能將是有益的如果你想獲得特定的行,例如總是每個的最新記錄。但由於您沒有提供datetime專欄,我剛剛通過Masterid任意訂購。