I'm interested in knowing if there's a better/cleaner/more efficient way, to obtain totals and subtotals within a query, than my solution below.
The query works fine but I'm just intrigued to know if there is cleaner solution. The data are results from a survey and i'm obtaining the counts per question within a zone and an overall zone count.
With Cte1 (ZoneId, QuestionId, Count1)
AS
(
Select
tz.ZoneId,
qn.QuestionId,
Count(1) as Count1
From
Customers cust
Inner Join Shops td on td.ShopCode = cust.ShopCode
Inner Join Zones tz on tz.Id = td.SlsZone
Inner Join Responses res on res.SampleId = cust.SampleId
Inner Join QstNodes qn on qn.QuestionId = res.QstNodeId
Where
Event >= 201201 And Event <= 201212
Group BY
tz.ZoneId, qn.QuestionId
)
SELECT
ZoneId,
QuestionId
Count1,
(
SELECT SUM(Count1)
FROm Cte1 as innercte
Where innercte.ZoneId = outercte.ZoneId
)
as ZoneTotal
FROM
Cte1 outercte

rollup, but that depends on the database that you are using. – Gordon Linoff Jan 24 at 15:31