【问题标题】:I need some help here with SQL Sum function group by dates and group我需要一些关于 SQL Sum 函数按日期和组分组的帮助
【发布时间】:2011-01-18 21:12:15
【问题描述】:

我有一个名为 Table1 的表

案例编号 |年份 |月 |集团 |参加时间 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

如果我想得到这样的结果

年份 |月 |GroupHours| GroupHourTotal 2010 | 1 |16-20 | 9 2010 | 3 |2 | 2 2009 | 4 |0-5 | 2 2009 | 4 |16-20 | 5

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

选择年、月、组、参加时间、总和(参加时间)
从表 1
groupby Year,Month,hourattended,sum(hourattended)
按年份顺序排列

【问题讨论】:

    标签: sql


    【解决方案1】:

    不要按时间分组

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:
        
        select Year,Month,group,sum(hourattended)
        from Table1
        groupby Year,Monthorder by year desc
        

        【讨论】:

          【解决方案4】:

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

          选择年、月、组标题、 SUM(HoursAttended) 作为 HoursAttended 从案例 C 加入组 G ON C.GroupId = G.Id GROUP BY 年、月、 GroupTitle 按年份顺序排列

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

          【讨论】:

            猜你喜欢
            • 2019-10-01
            • 1970-01-01
            • 2011-08-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-05-15
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多