0

我有一个费用表,例如:

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
.
.
4

2 回答 2

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=使其稍快一些。

于 2013-03-13T20:37:24.040 回答
0

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

select worksheet, category, sum(cost) from DataTablegroup by worksheet, category order by worksheet
于 2013-03-13T20:52:59.390 回答