一个查询中有两个不同的group by子句?

时间:2011-02-23 21:10:41

标签: postgresql

第一次在这里发帖,SQl的新手,我不确定如何说出来但我会尽我所能。

我有一个问题:

select report_month, employee_id, split_bonus,sum(salary) FROM empsal
where report_month IN('2010-12-01','2010-11-01','2010-07-01','2010-04-01','2010-09-01','2010-10-01','2010-08-01') 
AND employee_id IN('100','101','102','103','104','105','106','107')
group by report_month, employee_id, split_bonus;

现在,对于此查询的结果,我想添加一个新列 split_bonus_cumulative ,这相当于在select子句中添加 sum(split_bonus)但是对于这种情况,团购应该只有report_month和employee_id。

有人能告诉我如何使用单个查询执行此操作吗?提前谢谢。

2 个答案:

答案 0 :(得分:3)

尝试:

SELECT
  report_month, 
  employee_id, 
  SUM(split_bonus), 
  SUM(salary) 
FROM 
  empsal
WHERE 
  report_month IN('2010-12-01','2010-11-01','2010-07-01','2010-04-01','2010-09-01','2010-10-01','2010-08-01')
AND 
  employee_id IN('100','101','102','103','104','105','106','107')
GROUP BY 
  report_month, 
  employee_id;

答案 1 :(得分:3)

假设您正在使用Postgres,您可能还会发现窗口函数很有用:

http://www.postgresql.org/docs/9.0/static/tutorial-window.html

除非我误会,否则你想要的东西类似于以下内容:

select report_month, employee_id, salary, split_bonus,
       sum(salary) over w as sum_salary,
       sum(split_bonus) over w as sum_bonus
from empsal
where ...
window w as (partition by employee_id);

CTE也很方便:

http://www.postgresql.org/docs/9.0/static/queries-with.html

WITH
rows as (
SELECT foo.*
FROM foo
WHERE ...
),
report1 as (
SELECT aggregates
FROM rows
WHERE ...
),
report2 as (
SELECT aggregates
FROM rows
WHERE ...
)
SELECT *
FROM report1, report2, ...