我创建了一个查询,它返回以下内容:
[Branch], [SaleDate], [ReceiptNo]
我的[SaleDate]
列是SaleMonth和SaleYear的串联,格式为'01 / 2013'
我需要的是这些结果以表格的形式出现:
每个[SaleDate]
每个[Branch]
每个行/列的值为COUNT([ReceiptNo]
)
任何指针都将非常感激。
提前致谢。
答案 0 :(得分:1)
使用PIVOT
表格运算符:
SELECT *
FROM
(
SELECT ReceiptNo, SaleDate, Branch
FROM tablename
) AS t
PIVOT
(
COUNT(ReceiptNo)
FOR SaleDate IN([01/2013], [02/2013], [03/2013], ...)
) AS p;
要动态执行此操作而不是手动列出SaleDate
的值,您必须使用动态SQL,如下所示:
DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);
select @cols = STUFF((SELECT distinct ',' +
QUOTENAME(SaleDate)
FROM tablename
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '');
SELECT @query = 'SELECT *
FROM
(
SELECT ReceiptNo, SaleDate, Branch
FROM tablename
) AS t
PIVOT
(
COUNT(ReceiptNo)
FOR SaleDate IN(' + @cols + ')) AS p;';
execute(@query);