sql – 如何将选择查询结果插入到PIVOT中

我正在使用SQL SERVER 2012.

查询:1

SELECT *
FROM (
    SELECT Insurance, ChargeValue, CreatedDate
    FROM dailychargesummary
    WHERE MonthName='June 2017'
) m
PIVOT (
    SUM(ChargeValue)
    FOR CreatedDate IN ([06/22/2017], [06/23/2017],[06/30/2017])
) n

上述查询的输出如下所示:

《sql – 如何将选择查询结果插入到PIVOT中》

现在我在Pivot查询中编辑了一个月的所有日期,如06/01/2017,06/02/2017等.在Google中搜索后,我得到以下查询以显示所有日期给出月数.

查询2:

DECLARE @month AS INT = 5
DECLARE @Year AS INT = 2016

;WITH N(N)AS 
(SELECT 1 FROM(VALUES(1),(1),(1),(1),(1),(1))M(N)),
tally(N)AS(SELECT ROW_NUMBER()OVER(ORDER BY N.N)FROM N,N a)
SELECT datefromparts(@year,@month,N) date FROM tally
WHERE N <= day(EOMONTH(datefromparts(@year,@month,1)))

输出如下所示:

《sql – 如何将选择查询结果插入到PIVOT中》

任何人都可以指导我如何在Query1中的枢轴内使用Query2来自动化日期.

最佳答案 您需要使用动态查询来动态获取数据透视表

首先将日期列表分配给变量.

Declare @pivot_list varchar(8000)= ''
DECLARE @month AS INT = 5
DECLARE @Year AS INT = 2016

;WITH N(N)     AS (SELECT 1 FROM(VALUES(1),(1),(1),(1),(1),(1))M(N)),
      tally(N) AS (SELECT ROW_NUMBER()OVER(ORDER BY N.N)FROM N,N a)
select @pivot_list = stuff((SELECT ','+quotename(convert(varchar(15),datefromparts(@year,@month,N),101)) 
                            FROM tally
                            WHERE N <= day(EOMONTH(datefromparts(@year,@month,1))) for xml path('')),1,1,'')


--Print @pivot_list

现在使用数据透视表列表中的@pivot_list变量

Declare @sql varchar(8000)
set @sql = '
SELECT *
FROM (
    SELECT Insurance, ChargeValue, CreatedDate
    FROM dailychargesummary
    WHERE MonthName='June 2017'
) m
PIVOT (
    SUM(ChargeValue)
    FOR CreatedDate IN ('+@pivot_list+')
) n'

--Print @sql

Exec @sql
点赞