Warm tip: This article is reproduced from serverfault.com, please click

Group by query with rollup

发布于 2020-11-28 01:18:33

I'm trying to make a query that shows me every region and then make a count to see how mano contracts I have per region, but somehow I'm getting an error on ROLLUP (BO2.area)

This is the query

SELECT
  CASE WHEN BO2.area IS NULL THEN ISNULL(BO2.area, 'TOTAL') ELSE BO2.area END Area,
  COUNT(BO.status = 'INSTALLED') Contracts
FROM
  BO2
  JOIN BO ON BO.bostamp = BO2.bo2stamp
GROUP BY
  ROLLUP (BO2.area)
Questioner
pauLo_0liveira
Viewed
11
David Browne - Microsoft 2020-11-28 09:20:30

Should use GROUPING instead of a null check, and inside the aggregate you need a CASE expression. So:

SELECT
  CASE WHEN GROUPING(BO2.area)=1 THEN 'TOTAL' ELSE BO2.area END Area,
  SUM( CASE WHEN BO.status = 'INSTALLED' THEN 1 ELSE 0 END ) Contracts
FROM
  BO2
  JOIN BO ON BO.bostamp = BO2.bo2stamp
GROUP BY
  ROLLUP (BO2.area)