Create/Append table with sum of values grouped in different categories

橙三吉。 提交于 2019-12-13 21:44:10

问题


I have an expense table like:

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

This is how I am doing it right now:

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'

And If I don't use the top 1 then I get the same sums repeated over like thousands of rows. Also, my way of doing it only accounts for 1 workweek. :(

I want to create a Table with each workweeks total expense depending in each category something like :

WorkWeek1   Cat1TotalCost   Cat2TotalCost   Cat3TotalCost
WorkWeek2   Cat1TotalCost   Cat2TotalCost   Cat3TotalCost
.
.

回答1:


Try this:

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

Now, you are grouping by the workweek field. Also, I changed the like to = to make it slightly faster.




回答2:


Looks like you have many categories, are you looking for a grouping ?

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


来源:https://stackoverflow.com/questions/15395776/create-append-table-with-sum-of-values-grouped-in-different-categories

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!