2017-10-16 64 views
0

我試圖篩選一個表,其中有多個行,針對每個商店的單個成員他們已經購買了項目。加上購買肉類和蔬菜物品數量的列。我想要一份人員名單和他們購買肉類的所有商店的名單蔬菜。使用SQL來篩選表中我需要根據另一列累加多列的行

源表:

MemberId | StoreId | Meat | Vegegetables 1 11 1 2 1 12 0 1 1 14 1 2 2 12 1 0 3 12 1 0 3 12 1 0 4 11 2 1 4 13 0 1 4 14 0 1

我想申請的過濾器是:

對於成員Id(所有商店):WHERE SUM(肉類)> 0 AND SUM(蔬菜)> 0

所以我在尋找這個結果表

MemberId | StoreId | Meat | Vegetables 1 11 1 2 1 12 0 1 1 14 1 2 4 11 2 1 4 13 0 1 4 14 0 1

這讓我很難過,我無法弄清楚如何過濾這張表。

感謝

回答

1

這可以通過使用sum窗函數來完成。

select * from (
select t.*,sum(meat) over(partition by memberid) as meat_sum,sum(vegetables) over(partition by memberid) as veg_sum 
from source_table t 
) t 
where meat_sum>0 and veg_sum>0 
+0

感謝您的快速,正確,答案。 –

0

你可以使用CTE:

;WITH CTE AS 
(
    SELECT  MemberID      , 
       SUM(Meat)  AS Meat  , 
       SUM(Vegetables) AS Vegetables 
    FROM  Table 
    GROUP BY MemberID 
) 
SELECT   Table.* 
FROM   Table 
INNER JOIN  CTE ON CTE.MemberID = Table.MemberID 
WHERE   CTE.Meat > 0 AND CTE.Vegetables > 0; 
0

最簡單的方法我能想到的:

create table #test (MemberID int, StoreID int, Meat int, Vegetables int) 

    insert into #test values (1, 11, 1, 2) 
    insert into #test values (1, 12, 0, 1) 
    insert into #test values (1, 14, 1, 2) 
    insert into #test values (2, 12, 1, 0) 
    insert into #test values (3, 12, 1, 0) 
    insert into #test values (3, 12, 1, 0) 
    insert into #test values (4, 11, 2, 1) 
    insert into #test values (4, 13, 0, 1) 
    insert into #test values (4, 14, 0, 1) 

    Select * 
    from #test 
    where MemberID in (Select MemberId 
     from #test 
     group by MemberId, storeID 
     having sum(Meat)>0 and sum(vegetables)>0)