2012-07-27 63 views
3

我有一個表,看起來下如何做的套組在SQL Server和篩選記錄

 
SALES_ORDER_ID DATEDIFFERENCE FLAG 
1    -40    1 
1    -20    1 
2    40    0 
2    -10    1 
3    12    0 
4    -70    1 
5    60    0 
5    23    0 

// DDL

Declare @t table (sales_order_id int,DateDifference int, Flag int) 
Insert Into @t 
       Select 1,-40,1 Union All Select 1,-20,1 Union All 
       Select 2,40,0 Union All Select 2,-10,1 Union All 
       Select 3,12,0 Union All Select 4,-70,1 Union All 
       Select 5,60,0 Union All Select 5,23,0 
Select * 
From @t 

輸出應該

sales_order_id DateDifference Flag 
3      12   0 
5      60   0 
5      23   0 

即羣組(Sales_Order_Id)所有項目都具有標示爲0。

我的意思是Sales_Order_Id = 2將不會出現,因爲至少一個項目不爲零(2,-10,1)

請不要問我,如果信息不充分。

如何做這個查詢?

編輯

我發現我的答案..雖然仍然在尋找一個更優雅的一個

;with cte as(
    Select 
     sales_order_id = Case when x.sales_order_id is null then y.sales_order_id else x.sales_order_id end 
     ,x.CountFor0 
     ,y.CountFor1 
    From 
      (Select sales_order_id,CountFor0 = count(*) 
      from @t 
      where Flag = 0 
      group by sales_order_id)x 
    Full Join 

      (Select sales_order_id,CountFor1 =count(*) 
      from @t 
      where Flag = 1 
      group by sales_order_id)y 
    On x.sales_order_id = y.sales_order_id) 

    Select * 
    From cte 
    where CountFor1 is null 

感謝所有

因爲我沒有太多的聲譽,所以不能發佈我的答案部分的答案

+2

不知道爲什麼我一直downvoted ..是否有任何錯誤的問題我問過嗎? – 2012-07-27 04:02:51

+0

歡迎來到Stackoverflow並祝賀你回答你自己的問題! – 2012-07-27 04:34:26

+0

好工作! +1回答你自己的問題! – hmmftg 2012-07-27 04:43:59

回答

1

試試這個..

SELECT sales_order_id,DateDifference,Flag FROM @t WHERE sales_order_id NOT IN 
(SELECT sales_order_id FROM @t WHERE Flag=1) 
1

美好的一天!

我認爲,這將有助於:

Select * from @t WHERE FLAG=0; 
+0

我問了關於該集...這將不會給出慾望輸出 – 2012-07-27 03:58:57

1

好了,現在我明白你正在嘗試做的。您可以使用NOT EXISTS,正如其他人建議(sqlfiddle):

SELECT * 
FROM @t T1 
WHERE Flag = 0 
AND NOT EXISTS (
    SELECT * 
    FROM @t T2 
    WHERE T1.sales_order_id = T2.sales_order_id 
    AND T2.Flag <> 0) 

您還可以使用NOT IN,正如其他人還建議(sqlfiddle):

SELECT * 
FROM @t T1 
WHERE Flag = 0 
AND sales_order_id NOT IN (
    SELECT sales_order_id 
    FROM @t T2 
    WHERE T2.Flag <> 0) 

而且你甚至可以用一個JOIN和檢查連接表沒有行(id爲NULL)(sqlfiddle):

SELECT * 
FROM @t T1 
LEFT OUTER JOIN @t T2 ON T1.sales_order_id = T2.sales_order_id AND T2.Flag <> 0 
WHERE T1.Flag = 0 
AND T2.sales_order_id IS NULL 

原來的答覆:

你需要一個WHERE clause篩選結果:

SELECT * 
FROM @t 
WHERE Flag = 0 

退房here

我假設你的sqlfiddle也想在結果中(2,40,0)行,雖然。

0
select * 
from @T as T1 
where not exists(select * 
       from @T as T2 
       where T1.sales_order_id = T2.sales_order_id and 
         T2.Flag = 1) 
0

試試這個:

Select * From @t 
where Flag=0 and sales_order_id not in 
(select sales_order_id from @t where Flag !=0) 
1

我只是想補充一點,這是使用Windows功能的好地方:

select sales_order_id, DateDifference, flag 
from (select t.*, SUM(flag) over (partition by sales_order_id) as sumflag 
     from @t t 
    ) t 
where sumflag = 0