按字段选择记录顺序,并按相同字段获取SUM组

时间:2018-10-04 14:54:25

标签: mysql sql aggregate-functions

我试图按字段(例如项目)排序记录,并计算按同一字段分组的某些字段。

例如

Project    |    Worked By      |    Hours
------------------------------------------------
Data Entry |    Rakesh Malakar |    40.0
Data Entry |    Najar Man      |    25.0
                               |    65.0
Editing    |    Henry Bdr.     |    20.0
Editing    |    Jack Pd.       |    15.5
                               |    35.5

我在数据库上有一个相似的数据集。我只需要按project字段分组的总和即可。

我尝试了查询:

SELECT project, user as worked_by, hours, SUM(hours) as project_sum_hours
FROM project_hours
ORDER BY project
GROUP BY project

查询仅返回每个project字段的汇总记录。

2 个答案:

答案 0 :(得分:1)

您可以使用WITH ROLLUP来计算超级聚合。

尝试以下操作:

SELECT project, 
       user as worked_by, 
       SUM(hours) as hours 
FROM project_hours
GROUP BY project, worked_by WITH ROLLUP

答案 1 :(得分:1)

我认为您可能需要UNION ALL才能获得所需的结果:

SELECT project, user as worked_by, SUM(hours) as project_sum_hours
FROM project_hours
GROUP BY project, user
UNION ALL
SELECT project, NULL, SUM(hours) as project_sum_hours
FROM project_hours
GROUP BY project
ORDER BY project, (worked_by IS NULL) DESC;

ROLLUP很方便,但是会产生比您想要的更多的行。而且MySQL还不支持GROUPING SETS