我需要一些关于日期和组的SQL Sum功能组的帮助

时间:2011-01-18 21:12:15

标签: sql

我有一个名为Table1的表

CaseNumber | Year  | Month | Group    | HoursAttended
1          | 2010  |   1   |   16-20  |  8
2          | 2010  |   1   |   16-20  |  1
3          | 2010  |   2   |    0-5   |  2
4          | 2009  |   4   |    0-5   |  2
4          | 2009  |   4   |  16-20   |  5

如果我想得到这样的结果

Year | Month |GroupHours| GroupHourTotal 
2010 | 1     |16-20     | 9
2010 | 3     |2         | 2
2009 | 4     |0-5       | 2
2009 | 4     |16-20     | 5

我试过这个,但是当日期不在同一个月时,我得到的结果不正确。 有什么想法吗?

select Year,Month,group,hourattended,sum(hourattended)
from Table1
groupby Year,Month,hourattended,sum(hourattended)
order by year desc

4 个答案:

答案 0 :(得分:3)

请勿按照小组进行分组

select Year,Month,group,sum(hourattended) grouphourtotal
from Table1
group by Year,Month,group
order by year desc, month desc

这必须是伪的,否则根据需要引用“组”列名称

答案 1 :(得分:2)

仅按结果集中未聚合的列进行分组。由于您总结了HoursAttended,因此它不属于您的GROUP BY。

select Year,Month,group,hourattended,sum(hourattended) from Table1 groupby Year,Month order by year desc

答案 2 :(得分:1)


select Year,Month,group,sum(hourattended)
from Table1
groupby Year,Monthorder by year desc

答案 3 :(得分:1)

您有一个依赖字段Group,需要将其分成单独的表。一旦你这样做,它就是小菜一碟:

  

SELECT Year,Month,GroupTitle,   SUM(HoursAttended)作为HoursAttended   来自案例C JOIN Groups G ON   C.GroupId = G.Id GROUP BY Year,Month,   GroupTitle ORDER BY year desc

将“Group”替换为“GroupId”,将其作为Groups表的外键,Bob是你的叔叔。