Saturday, February 25, 2012

Multiple select and sum expressions on the same table SQL…?

Little complex but I'll try to explain the best I can
I have the following table…

UserID___Year___Month_____A1____A2____B1____B2

__1_______4______5______45_____5____43____0

__1_______4______6______10_____12___1_____3

__1_______5______5______12_____22___8_____7

__1_______5______6______11_____10___5_____0

__2_______4______5______9______65___33____66

__2_______4______6______3______3____10____11

__2_______5______5______44_____2___77_____1

I want to pull out the data to show the sum of the totals for each year the user is in. The idea is to then be able to see a comparison for year on year on a month by month basis

Eg.

UserID____TotalAYear4____TotalBYear4___TotalAYear5____TotalBYear5___Month

__1___________50_____________43___________34____________15__________5

__1___________22_____________4____________21____________5___________6

__2___________74_____________99___________21____________5___________5

There would be no data returned for UserID2 for month 6 as there is no data for them for year 5 month 6 therefore no comparison can be made.

I've having real difficulty getting the correct SQL syntax to do this. Any ideas or pointers would be great thanks

Thebest, most scalable way to do this would be to aggregate by month and year, and let the client-side code calculate the comparisons. So a simple:
SELECT UserID, Year, Month, SUM(A1 + A2) AS TotalA, SUM(B1 + B2) AS TotalB
FROM Table
GROUP BY UserID, Month, Year
Youcould pivot the data out, but you would need to go in and change the code with each new year that you add, and it would quickly become cumbersome...

No comments:

Post a Comment