以下是一种快速而肮脏的方法,就像jayvee建议的那样。它只有在查询的第一列是可以放入字符串的类型时才有效。如果不是,您可以将摘要输出移动到另一列。
DECLARE @TestData as TABLE (Col1 nvarchar(50), Col2 nvarchar(50), Col3 nvarchar(50));
Insert Into @TestData
Select 'Whatever1', 'Day1', 'Text1'
UNION ALL Select 'Whatever1', 'Day2', 'Text1'
UNION ALL Select 'Whatever1', 'Day3', 'Text2'
UNION ALL Select 'Whatever2', 'Day1', 'Text1'
UNION ALL Select 'Whatever2', 'Day2', 'Text3'
UNION ALL Select 'Whatever3', 'Day1', 'Text3'
UNION ALL Select 'Whatever3', 'Day2', 'Text2'
UNION ALL Select 'Whatever3', 'Day3', 'Text3';
With OriginalQuery as (
--This should be your original query
Select Col1, Col2, Col3 from @TestData
), GroupData as(
-- This is the summary data you want
Select Col3, COUNT(Col3) as ColCount from OriginalQuery Group By Col3
)
Select * from OriginalQuery --Output the original data
UNION ALL
--This is formatting the group data,
--and adding null columns so it matches the original query length, or the union will fail
Select 'Number of ' + Col3 + ' = ' + Cast(ColCount as nvarchar(10)),
NULL, NULL --One for each column in original query except the first one
From GroupData;