如果总数为0,则删除结果组

时间:2019-05-13 09:59:42

标签: sql sql-server group-by

我正在使用下表创建堆积的条形图-它比这个大很多:

ID | Name | foodEaten | total
1  | Sam  | Burger    | 3
1  | Sam  | Pizza     | 1
1  | Sam  | Kebab     | 0
1  | Sam  | Cheesecake| 3
1  | Sam  | Sandwich  | 5
2  | Jeff | Burger    | 0
2  | Jeff | Pizza     | 0
2  | Jeff | Kebab     | 0
2  | Jeff | Cheesecake| 0
2  | Jeff | Sandwich  | 0

我需要找到一种方法来删除类似Jeff的结果。他所吃的食物总数为0。我想不出最简单的方法来实现这一目标。我已经尝试将整个结果按ID分组并创建总计,但是这只是没有发生。

如果该人总共吃了0种食物,则需要将其排除在外。但是,如我的上表所示,如果他没有吃过任何东西,也没有吃过烤肉串,则需要将其包括在结果中!

所以需要的输出是:

ID | Name | foodEaten | total
1  | Sam  | Burger    | 3
1  | Sam  | Pizza     | 1
1  | Sam  | Kebab     | 0
1  | Sam  | Cheesecake| 3
1  | Sam  | Sandwich  | 5

6 个答案:

答案 0 :(得分:2)

假设您希望数据按原样显示,而不是汇总出来,然后排除:

WITH CTE AS (
    SELECT ID,
           [Name],
           foodEaten,
           total,
           SUM(total) OVER (PARTITION BY [Name]) AS nameTotal
    FROM YourTable)
SELECT ID,
       [Name],
       foodEaten,
       total
FROM CTE
WHERE nameTotal > 0;

答案 1 :(得分:0)

您可以在下面尝试-

select id,name
from tablename a
group by id,name
having sum(total)>0 

OR

DEMO

select * from tablename a 
where not exists (select 1 from tablename b where a.id=b.id group by id,name
having sum(total)=0)

答案 2 :(得分:0)

select id, name, foodEaten, sum(total) as total from <table> group by ID having sum(total) > 0

这对您有用吗?

答案 3 :(得分:0)

DELETEHAVING SUM(total) = 0一起使用将删除结果总数为0的结果组

DELETE FROM TableName
WHERE ID IN (SELECT Id FROM TableName GROUP BY ID HAVING SUM(total) = 0)

或者如果您想删除并且仅选择总计为零的记录,则

SELECT * FROM TableName
WHERE ID NOT IN (SELECT Id FROM TableName GROUP BY ID HAVING SUM(total) = 0)

答案 4 :(得分:0)

尝试一下

;WITH CTE (ID , Name , foodEaten , total)
AS
(
SELECT 1  , 'Sam'  , 'Burger'    , 3 UNION ALL
SELECT 1  , 'Sam'  , 'Pizza'     , 1 UNION ALL
SELECT 1  , 'Sam'  , 'Kebab'     , 2 UNION ALL
SELECT 1  , 'Sam'  , 'Cheesecake', 3 UNION ALL
SELECT 1  , 'Sam'  , 'Sandwich'  , 5 UNION ALL
SELECT 2  , 'Jeff' , 'Burger'    , 0 UNION ALL
SELECT 2  , 'Jeff' , 'Pizza'     , 0 UNION ALL
SELECT 2  , 'Jeff' , 'Kebab'     , 0 UNION ALL
SELECT 2  , 'Jeff' , 'Cheesecake', 0 UNION ALL
SELECT 2  , 'Jeff' , 'Sandwich'  , 0
)
SELECT ID , Name ,SUM( total)  AS Grandtotal
FROM CTE
GROUP BY  ID , Name 
HAVING SUM( total) >0

结果

ID  Name    Grandtotal
----------------------
1   Sam         14

答案 5 :(得分:0)

假设total永远不会为负,那么可能最有效的方法是使用exists

select t.*
from t
where exists (select 1
              from t t2
              where t2.name = t.name and
                    t2.total > 0
             );

尤其是,这可以利用(name, total)上的索引。