我有桌子工作者
id name
----------- -------------------
5 Артур Петрович
6 Дмитрий Белов
7 Казарян Артур
和另一张表
id date amount id_worker
----------- ---------- ----------- -----------
27 2013-09-12 1500 5
28 2013-09-12 100 6
29 2013-09-12 500 5
30 2013-09-12 500 6
31 2013-09-14 1000 7
32 2013-09-15 100 5
33 2013-09-15 200 5
我想编写存储过程,在输入中获取开始和结束日期
在输出我想得到这个表如果:
开课日期:2013-09-10
截止日期:2013-09-15
Name 2013-09-10 2013-09-11 2013-09-12 2013-09-13 2013-09-14 2013-09-15
_______________ __________ __________ __________ __________ __________ __________
Артур Петрович 0 0 2000 0 0 300
Дмитрий Белов 0 0 600 0 0 0
Казарян Артур 0 0 0 0 1000 0
答案 0 :(得分:2)
我唯一能做到这一点的方法是使用Dynamic SQL
,如果提前知道表格结构,IMO不存在SQL Injection
的风险
DECLARE @DateList VARCHAR(MAX), @DateListCoalesced VARCHAR(MAX)
SELECT @DateList = '', @DateListCoalesced = ''
;WITH DateLimits AS (
SELECT CAST('2013-9-10' AS DATE) AS dt
UNION ALL
SELECT DATEADD(dd, 1, dt)
FROM DateLimits s
WHERE DATEADD(dd, 1, dt) <= CAST('2013-9-15' AS DATE))
SELECT @DateList = @DateList + '[' + CAST(dt AS VARCHAR)+ '], ' ,
@DateListCoalesced = @DateListCoalesced + ' COALESCE( [' + CAST(dt AS VARCHAR)+ '] , 0) as [' + CAST(dt AS VARCHAR)+ '], '
FROM DateLimits
;SET @DateList = LEFT(@DateList, LEN(@DateList) - 1)
;SET @DateListCoalesced = LEFT(@DateListCoalesced, LEN(@DateListCoalesced) - 1)
DECLARE @query NVARCHAR(max)
SET @query = N'SELECT [Name], ' + @DateListCoalesced +'
FROM
(SELECT [Name], [Date], [Amount]
FROM WorkerAmount
INNER JOIN Worker ON WorkerAmount.id_worker = Worker.id
) p
PIVOT
(
Sum ([Amount] )
FOR [Date] IN ( '+ @DateList +' )
) AS pvt '
EXEC sp_executesql @Query
这个答案使用了其他几个问题的组合