我正在尝试编写动态数据透视sql语句。我需要计算每个销售员的日期总和(amt),其中日期是在动态输入范围之间取得的
这是我的表。:
来源表
╔Sman_name date amt
aaa 2014-09-20 100
bbb 2014-09-22 200
aaa 2014-09-20 150
aaa 2014-09-22 200
我应该得到以下结果:
2014-09-20 2014-09-21 2014-09-22
aaa 250 0 200
bbb 0 0 200
如何使用数据透视查询实现此目的? 谢谢你的帮助
答案 0 :(得分:0)
首先,您需要一个查询,该查询生成两个日期之间的序列日期,这将是动态数据透视表的列名称的来源。 其次,因为您需要0表示空值,对于每个dyncamic列,需要构建ISNULL检查。
检查以下解决方案
DECLARE @startDate date = '2014-09-20'
DECLARE @endDate date = '2014-09-25'
DECLARE @sql NVARCHAR(MAX)
DECLARE @dates NVARCHAR(MAX)
-- to add ISNULL(columnName,0) to return 0 if null
DECLARE @nullChecks NVARCHAR(MAX)
--CTE for generating serial dates
;WITH Dates([Date])
AS
(
--Start with the first date
SELECT @startDate
UNION ALL
-- Loop by joining the CTE Dates, until the date < @endDate
SELECT DATEADD(DD,1,Dates.[Date])
FROM Dates
WHERE Dates.[Date] < @endDate
)
SELECT @dates = COALESCE(@dates + '],[', '') + CAST([Date] AS VARCHAR(10)),
@nullChecks = COALESCE(@nullChecks + 'ISNULL([', '') +
CAST([Date] AS VARCHAR(10)) + '],0) AS ['+CAST([Date] AS VARCHAR(10))+'] ,'
FROM Dates
--Append ISNULL condition in the beginnig
SET @nullChecks = 'ISNULL([' + SUBSTRING(@nullChecks,1,LEN(@nullChecks)-1)
SET @sql ='
SELECT sman_name,' + @nullChecks + ' FROM yourTableName
PIVOT
(
SUM(amt) FOR [date] IN ([' + @dates + '])
) As P;'
PRINT @sql
EXEC sp_executesql @sql