使用SQL Server 2008 R2在两个日期之间的数据透视表

时间:2014-11-07 06:21:26

标签: sql-server sql-server-2008-r2 pivot

我有下表:

示例

create table test
(
  col_dt1 date,
  col_dt2 date
)

插入一些记录:

insert into test values('2014-11-07','2014-12-01');

select * from test;

col_dt1     col_dt2
----------------------
2014-11-07  2014-12-01

预期结果:

col_dt1     col_dt2    07 November 2014  08 November 2014 .................... 01 December 2014
-----------------------------------------------------------------------------------------------
2014-11-07  2014-12-01       1                 0          ....................        1

我坚持要在两个日期之间获取所有日期以在数据透视表中显示填充列。

1 个答案:

答案 0 :(得分:2)

DECLARE @Start_Date DATE, @End_Date DATE, @QUERY NVARCHAR(MAX), @SUBQUERY NVARCHAR(MAX), @ROWCOUNT int

CREATE TABLE #TempTable(
ID int IDENTITY(1,1) NOT NULL,
Start_Date date,
End_Date date, 
Dates NVARCHAR(50),
HasDate int
)
CREATE TABLE #TempTable2(
Start_Date date,
End_Date date, 
Dates NVARCHAR(50), 
HasDate int
)

SET @Start_Date = (SELECT TOP 1 col_dt1 from test)
SET @End_Date = (SELECT TOP 1 col_dt2 from test)

INSERT INTO #TempTable
SELECT 
@Start_Date as Start_Date,
@End_Date as End_Date,
RIGHT(REPLICATE('0', DAY(DATEADD(DAY,number,@Start_Date))) + CAST(DAY(DATEADD(DAY,number,@Start_Date)) AS NVARCHAR(2)), 2)
+' '+DATENAME(MONTH,DATEADD(DAY,number,@Start_Date))+' '+CONVERT(NVARCHAR(50),YEAR(DATEADD(DAY,number,@Start_Date))) as Start_Date,
HasDate =
      CASE 
         WHEN DATEADD(DAY,number,@Start_Date)=@Start_Date THEN 1
         WHEN DATEADD(DAY,number,@Start_Date)=@End_Date THEN 1
         ELSE 0
      END
FROM master..spt_values
WHERE type = 'P'
AND DATEADD(DAY,number,@Start_Date) <= @End_Date
INSERT INTO #TempTable2 SELECT [Start_Date],[End_Date],[Dates],HasDate FROM #TempTable

SELECT * FROM #TempTable

SET @QUERY=''
SET @QUERY+='SELECT * FROM #TempTable2
                PIVOT
                (
                    Max(HasDate)
                    FOR Dates IN ('

SET @SUBQUERY=''
SET @ROWCOUNT=1                 
WHILE @ROWCOUNT <= (SELECT COUNT(*) FROM #TempTable)
BEGIN
    SET @SUBQUERY=@SUBQUERY+'['+(SELECT CONVERT(NVARCHAR(50),Dates)as Dates FROM #TempTable WHERE ID=@ROWCOUNT)+']'
    IF (@ROWCOUNT<>(SELECT COUNT(*) FROM #TempTable))
    BEGIN
        SET @SUBQUERY=@SUBQUERY+','
    END
    SET @ROWCOUNT=@ROWCOUNT+1
END             
SET @QUERY=@QUERY+@SUBQUERY+')
                )AS tblPivot'


PRINT(@QUERY)
EXECUTE(@QUERY)

DROP TABLE #TempTable
DROP TABLE #TempTable2

你可以试试这个。