从SQL

时间:2017-01-12 10:41:48

标签: sql sql-server

我有一张包含以下信息的表格

ID, USER, DATE, AMOUNT
id1, user2, 01/02/2015, 100
id2, user1, 03/02/2015, 200
id3, user2, 06/02/2015, 400
id4, user3,  04/02/2015, 900

我想要获得的是一个表,其中列出了[min_date,max_date]间隔中的所有日期以及每个用户的相应值。

USER, user1, user2, user3
01/02/2015,  0, 100, 0
02/02/2015, 0, 0, 0
03/02/2015, 300, 0, 0
04/02/2015, 0, 0, 900
05/02/2015, 0, 0, 0
06/02/2015, 0, 400, 0

我正在使用this post中建议的技术生成一列日期。

WITH Dates AS (
        SELECT
         [Date] = CONVERT(DATE,'01/01/2011', 103)
        UNION ALL SELECT
         [Date] = DATEADD(DAY, 1, [Date])
        FROM
         Dates
        WHERE
         Date < CONVERT(date, '30/11/2016', 103)
) SELECT
 [Date]
FROM
 Dates
 OPTION (MAXRECURSION 10000)
 --OPTION (MAXRECURSION 45)

1 个答案:

答案 0 :(得分:1)

试试这个:

CREATE TABLE IDS (ID CHAR(100), USERS CHAR(100), DATES  CHAR(100), AMOUNT  INT)
INSERT INTO IDS VALUES ('id1', 'user2', '01/02/2015', 100)
INSERT INTO IDS VALUES ('id2', 'user1', '03/02/2015', 200)
INSERT INTO IDS VALUES ('id3', 'user2', '06/02/2015', 400)
INSERT INTO IDS VALUES ('id4', 'user3', '04/02/2015', 900)


WITH Dates AS (
        SELECT
         [Date] = CONVERT(DATE,'02/01/2015', 103)
        UNION ALL SELECT
         [Date] = DATEADD(MONTH, 1, [Date])
        FROM
         Dates
        WHERE
         Date < CONVERT(date, '30/12/2015', 103)
)

SELECT [Date] AS [USER] INTO [DATE] FROM Dates OPTION (MAXRECURSION 1200)



select [DATE].[USER],COALESCE ([user1],0) AS 'user1',COALESCE ([user2],0) AS 'user2',COALESCE ([user3],0) AS 'user3'
from 
(
  select DATES, USERS, AMOUNT
  from IDS
) src
pivot
(
  sum(AMOUNT)
  for USERS in ([user1], [user2], [user3])
) piv
RIGHT JOIN [DATE] ON [DATE].[USER]=PIV.DATES