开发者

Two different group by clauses in one query?

First time posting here, a newbie to SQl, and I'm not exactly sure how to word this but I'll try my best.

I have a query:

select report_mo开发者_JAVA技巧nth, 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;

Now, to the result of this query, I want to add a new column split_bonus_cumulative that is essentially equivalent to adding a sum(split_bonus) in the select clause but for this case, the group buy should only have report_month and employee_id.

Can anyone show me how to do this with a single query? Thanks in advance.


Try:

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;


Assuming you're using Postgres, you might also find window functions useful:

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

Unless I'm mistaking, you want something that resembles the following:

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);

CTEs are also convenient:

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, ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜