我有一张看起来像下面的桌子
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
谢谢大家
由于我没有太多声誉,因此无法在答案部分发布我的答案