如何用条件做一个Sum()?

时间:2015-09-23 04:36:23

标签: dynamic sql-server-2012 sum grouping case-when

我有一个像这样的表

+----+------+-----+
| ID | Type | Qty |
+----+------+-----+
| 1  | 1    | 10  |
| 2  | 1    | 10  |
| 3  | 2    | 15  |
| 4  | 1    | 20  |
| 5  | 2    | 10  |
+----+------+-----+

如何根据条件进行动态求和" Type"字段。

这样的事情:

SELECT 
    Type, 
    CASE WHEN Type = 1 THEN SUM(Qty) 
         ELSE Qty 
    END AS SumQty
FROM tbl
GROUP BY ?? 

我想要一个这样的结果:

+------+--------+
| Type | SumQty |
+------+--------+
| 1    | 40     |
| 2    | 15     |
| 2    | 10     |
+------+--------+

我知道我可以使用UNION子句执行此操作。但是如果你知道一个动态查询来实现这个结果,请告诉我。 任何解决方案将不胜感激。感谢

1 个答案:

答案 0 :(得分:0)

您可以执行两个查询,一个用于您想要的类型,一个用于所有其他查询,然后将它们组合在一起,例如:

confirm

sqlfiddle中测试:

select type, sum(qty) as sumqty from tbl where type = 1 group by type
union all
select type, qty as sumqty from tbl where type <> 1

给你你想要的东西:

create table tbl (id int, type int, qty int);
insert into tbl (id, type, qty) values (1, 1, 10);
insert into tbl (id, type, qty) values (2, 1, 10);
insert into tbl (id, type, qty) values (3, 2, 15);
insert into tbl (id, type, qty) values (4, 1, 20);
insert into tbl (id, type, qty) values (5, 2, 10);
===
select type, sum(qty) as sumqty from tbl where type = 1 group by type
union all
select type, qty as sumqty from tbl where type <> 1