在子查询中添加总和

时间:2017-01-12 21:08:24

标签: sql postgresql aggregate-functions

我想在底部添加一个Total,似乎无法理解如何让语法向我展示' Total'在底部。我花了很多时间在网上搜索它。我需要coalesce片段,因为我需要为没有Sales的Employees显示零。我看了一下这个链接,但我需要在coalesce中使用 Zero

Add a row for TOTAL in a sql query result

select t2.Employee, coalesce(t1."This Week",0) "This Week"
from mytable t2 left outer join
(select case when grouping(Employee) = 1 then 'Total' else Employee end, sum(Sales) "This Week"
from information
where Week >= DATE '01/01/2017' and Week < DATE '01/31/2017'
and LastUpdate >= DATE '01/01/2017' and LastUpdate < DATE '01/31/2017'
group by Employee with Rollup) t1
on t1.Employee = t2.Employee

结果:

Employee                    This Week 

 Batman                       15
 Penguin                      25
 Joker                        0
 Bane                         5
 Scarecrow                    0
 ------------------->         45

错误:

ERROR:  syntax error at or near "with"
LINE 8: group by Employee with Rollup) t1

2 个答案:

答案 0 :(得分:1)

您可以使用ROLLUP

尝试此操作
SELECT coalesce(Employee,'Total'),
       "This Week"
FROM
  (SELECT t2.Employee,
          coalesce(sum(t1.Sales),0) "This Week"
   FROM mytable t2
   LEFT JOIN information t1 ON t1.Employee = t2.Employee
   AND t1.Week >= DATE '01/01/2017'
   AND t1.Week < DATE '01/31/2017'
   AND t1.LastUpdate >= DATE '01/01/2017'
   AND t1.LastUpdate < DATE '01/31/2017'
   GROUP BY rollup(t2.Employee)
  ) x

答案 1 :(得分:1)

您不需要外部查询。除了Week和LastUpdate的条件之外,不涉及join操作;你可以将它们移动到WHERE子句(无论如何PostgreSQL优化器应该自己做,但这样你的查询就更清楚了):

SELECT
  COALESCE(t2.Employee, 'Total') AS Employee,
  COALESCE(SUM(t1.Sales), 0) AS "This Week"
FROM mytable t2
LEFT JOIN information t1 USING (Employee)
WHERE t1.Week BETWEEN DATE '01/01/2017' AND DATE '01/31/2017'
  AND t1.LastUpdate BETWEEN DATE '01/01/2017' AND DATE '01/31/2017'
GROUP BY GROUPING SETS ((t2.Employee), ());