gpt4 book ai didi

dynamic - 如何做有条件的 Sum()?

转载 作者:行者123 更新时间:2023-12-02 04:46:02 25 4
gpt4 key购买 nike

我有一个这样的表

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

如何根据条件“类型”字段进行动态求和。

像这样:

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

关于dynamic - 如何做有条件的 Sum()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32731053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com