创建/附加表,其中包含按不同类别分组的值的总和

时间:2013-03-13 20:25:19

标签: sql-server sql-server-2008 append

我有一张费用表:

WorkWeek  Catg  Item    Cost
WorkWeek1 Cat1  Item1   Price
WorkWeek1 Cat1  Item2   Price
WorkWeek1 Cat1  Item3   Price
WorkWeek1 Cat1  Item4   Price
WorkWeek1 Cat2  Item1   Price
WorkWeek1 Cat2  Item5   Price
WorkWeek1 Cat2  Item6   Price
WorkWeek1 Cat3  Item1   Price
WorkWeek1 Cat3  Item5   Price
.
.
WorkWeekA CatB  ItemC   Price

这就是我现在正在做的事情:

select top(1)
     (select sum(cost) from DataTable where Catg like 'Cat1') as Cat1TotalCost
    ,(select sum(cost) from DataTable where Catg like 'Cat2') as Cat2TotalCost
    ,(select sum(cost) from DataTable where Catg like 'Cat3') as Cat3TotalCost
    .
    .
    .
    .
from DataTable where WorkWeek like 'WorkWeek1'

如果我不使用top 1那么我会得到相同数量的行重复的总和。另外,我这样做的方式只占每周工作1小时。 :(

我想创建一个表,每个工作周的总费用取决于每个类别,如:

WorkWeek1   Cat1TotalCost   Cat2TotalCost   Cat3TotalCost
WorkWeek2   Cat1TotalCost   Cat2TotalCost   Cat3TotalCost
.
.

2 个答案:

答案 0 :(得分:0)

试试这个:

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

现在,您正在按工作周字段进行分组。另外,我将like更改为=以使其稍快一些。

答案 1 :(得分:0)

看起来你有很多类别,你在寻找分组吗?

select worksheet, category, sum(cost) from DataTablegroup by worksheet, category order by worksheet