如何做有条件的 Sum()?

How to do a Sum() with condition?

我有一个Table这样的

+----+------+-----+
| 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 子句来做到这一点。但是,如果您知道实现该结果的动态查询,请告诉我。 任何解决方案将不胜感激。谢谢

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

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

sqlfiddle 中测试:

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

给你你想要的:

type    sumqty
----    ------
   1        40
   2        15
   2        10