gpt4 book ai didi

mysql - MySQL 中的嵌套 Group By 类型操作

转载 作者:行者123 更新时间:2023-11-29 00:11:16 24 4
gpt4 key购买 nike

假设我的 table 看起来像这样:

enter image description here

现在我可以通过简单的 Group By 获得 a、b 的完整总和,但是是否可以通过单个优化查询获得上述嵌套的 group-by 类型输出?

我现在使用的解决方法是检索 Cat1=a 的所有记录,然后在 Cat2 上应用分组依据。但是由于 Cat1 的数量很多(a、b、c、d...等),这就变成了太多的查询。

你有什么建议?

最佳答案

select cat1, 
sum(case when cat2='x' then val end) as sumValForX,
sum(case when cat2='y' then val end) as sumValForY
from your_table
group by cat1

SQLFiddle demo

关于mysql - MySQL 中的嵌套 Group By 类型操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24905323/

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