gpt4 book ai didi

sql - 将行数据分组并汇总到 MS-SQL 中的列中?

转载 作者:行者123 更新时间:2023-12-02 22:09:36 24 4
gpt4 key购买 nike

Original Question

我不知道我是应该打开一个新问题还是取消标记最后一个问题!所以,我想做的是:

WorkWeek  Catg  Item    Cost
WorkWeek1 Cat1 Item1 Price
WorkWeek1 Cat1 Item2 Price
WorkWeek1 Cat2 Item3 Price
WorkWeek1 Cat3 Item4 Price
WorkWeek1 Cat3 Item1 Price
WorkWeek2 Cat1 Item1 Price
WorkWeek2 Cat2 Item2 Price
WorkWeek3 Cat1 Item1 Price
WorkWeek4 Cat1 Item2 Price
.
.
WorkWeekA CatB ItemC Price

我想创建一个新表,列出每个工作周,然后列出该工作周内每个 catg 的总价格。这就是我现在正在做的,但查询只是将每个 ww 的所有内容加起来,给我所有工作周的总和:

select
workweek
,(select sum(cost) from DataTable where Catg = 'Cat1') as Cat1TotalCost
,(select sum(cost) from DataTable where Catg = 'Cat2') as Cat2TotalCost
,(select sum(cost) from DataTable where Catg = 'Cat3') as Cat3TotalCost
.
.
.
.
from DataTable
group by Workweek

最佳答案

你也可以像这样做枢轴:

select workweek,
sum(case when Catg = 'Cat1' then cost end) as Cat1TotalCost,
sum(case when Catg = 'Cat2' then cost end) as Cat2TotalCost,
sum(case when Catg = 'Cat3' then cost end) as Cat3TotalCost
from DataTable
group by Workweek

您不应该为每个值执行单独的子查询。

pivot 语句也是一个非常合理的选择。我倾向于坚持使用显式版本(上图),因为它让我在添加列时更加灵活。

关于sql - 将行数据分组并汇总到 MS-SQL 中的列中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15548055/

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