3

我有餐桌工人

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
4

1 回答 1

3

我知道这样做的唯一方法是使用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

这个答案结合了其他几个问题

于 2013-09-15T15:59:40.920 回答