gpt4 book ai didi

sql - 如何将选择查询结果插入 PIVOT

转载 作者:行者123 更新时间:2023-12-01 03:32:18 25 4
gpt4 key购买 nike

我正在使用 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

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

enter image description here

现在我在 Pivot Query 中硬编码了一个月的所有日期,例如 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)))

输出如下所示:

enter image description here

任何人都可以指导我如何使用 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

关于sql - 如何将选择查询结果插入 PIVOT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44978824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com