;WITH C as
(
SELECT FormID,
[Site 1],
[Site 2],
[Site 3],
(SELECT SUM(S)
FROM (VALUES([Site 1]),
([Site 2]),
([Site 3])) AS T(S)) as Total
FROM (SELECT Site, COUNT(FormID) AS NumberOfForms,FormID
FROM @CRFCount WHERE Present='Yes'
GROUP BY Site, FormID) d
PIVOT
(SUM(NumberOfForms)
FOR [Site] IN ([Site 1], [Site 2], [Site 3])
) AS p
)
SELECT *
FROM
(
SELECT FormID,
[Site 1],
[Site 2],
[Site 3],
Total
FROM C
UNION ALL
SELECT 'Total',
SUM([Site 1]),
SUM([Site 2]),
SUM([Site 3]),
SUM(Total)
FROM C
) AS T
ORDER BY CASE WHEN FormID = 'Total' THEN 1 END
Note: If you are using SQL Server 2005 you need to change this:
(SELECT SUM(S)
FROM (VALUES([Site 1]),
([Site 2]),
([Site 3])) AS T(S)) as Total
to
(SELECT SUM(S)
FROM (SELECT [Site 1] UNION ALL
SELECT [Site 2] UNION ALL
SELECT [Site 3]) AS T(S)) as Total
Try on SE Data
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…