1

我创建了一个查询,它返回以下内容:

[Branch], [SaleDate], [ReceiptNo]

我的[SaleDate]专栏是 SaleMonth 和 SaleYear 的串联,格式为“01/2013”

我需要的是这些结果以表格的形式出现:

每个列[SaleDate]

每人一行[Branch]

每行/列的值将是一个 COUNT( [ReceiptNo])

任何指针将不胜感激。

提前致谢。

4

1 回答 1

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);
于 2013-09-10T12:47:18.517 回答