我不知道如果我应该打开一个新问题或者只是取消标记最后一个问题! 所以,我想做的是:
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
答案 0 :(得分:3)
你也可以这样做:
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
声明也是一个非常合理的选择。我倾向于坚持使用显式版本(上图),因为它在添加列时给了我更多的灵活性。
答案 1 :(得分:2)
您可以使用PIVOT
表运算符来代替:
SELECT *
FROM
(
SELECT workweek, catg, cost
FROM datatable
) AS t
PIVOT
(
SUM(cost)
FOR catg IN (Cat1, Cat2, Cat3)
) AS p;
如果您不想手动列出catg
值,并且希望动态地对表中catg
的所有值执行此操作,则可以使用动态SQL动态执行此操作。类似的东西:
DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);
select @cols = STUFF((SELECT distinct ',' +
QUOTENAME(catg)
FROM datatable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '');
SELECT @query =
'SELECT
*
FROM
(
SELECT workweek, catg, cost
FROM datatable
) AS t
PIVOT
(
SUM(cost)
FOR catg IN ( ' + @cols + ')
) AS p';
EXECUTE( @query);