3

我有一张看起来像下面的桌子

SALES_ORDER_ID 日期差异标志
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

所有项目的标志都为 0 的组 (Sales_Order_Id)。

我的意思是 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

谢谢大家

由于我没有太多声誉,因此无法在答案部分发布我的答案

4

6 回答 6

1

尝试这个..

SELECT sales_order_id,DateDifference,Flag FROM @t WHERE sales_order_id NOT IN 
 (SELECT sales_order_id FROM @t WHERE Flag=1)
于 2012-07-27T07:24:22.483 回答
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
于 2012-07-27T15:47:18.867 回答
1

再会!

我认为这会有所帮助:

Select * from @t WHERE FLAG=0;
于 2012-07-27T03:29:34.343 回答
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)

您甚至可以使用 aJOIN并检查连接的表是否没有行(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子句来过滤结果:

SELECT * 
FROM @t
WHERE Flag = 0

在这里查看 sqlfiddle

不过,我假设您也想要(2,40,0)结果中的行。

于 2012-07-27T03:33:34.370 回答
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)
于 2012-07-27T05:22:37.023 回答
0

尝试这个:

Select * From @t 
where Flag=0 and sales_order_id not in 
(select sales_order_id from @t  where Flag !=0)
于 2012-07-27T06:50:28.730 回答