如何使用基于日期的PIVOT生成报告

时间:2016-07-12 08:35:44

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

我有两个表MasterTableTest8和HistoricDatatest8。

  create table MasterTableTest8
(ID int primary key, Name varchar(10))

insert into MasterTableTest8 values (1,'ATS')
insert into MasterTableTest8 values (2,'BTS')
 CREATE TABLE HistoricDatatest8
(
ID int FOREIGN KEY REFERENCES MasterTableTest8(ID),
Name varchar(100),
ShortName  varchar(10),
Reason varchar(10),
Importance varchar(10),
Noofissues int,
inserteddate datetime
)
insert into HistoricDatatest8 values (1,'ATS','S',   'Other','High',26,getdate()-7)
insert into HistoricDatatest8 values (1,'ATS','S',   'Other','High',8,getdate()+7)
insert into HistoricDatatest8 values (1,'ATS','S',   'Other','High',80,getdate())

insert into HistoricDatatest8 values (2,'BTS','S1',   'Other','LOW',26,getdate()-7)
insert into HistoricDatatest8 values (2,'BTS','S1',   'Other','LOW',8,getdate()+7)
insert into HistoricDatatest8 values (2,'BTS','S1',   'Other','LOW',80,getdate())
  

- 创建并插入两个表。

select 
N.ID,
N.Name,
ShortName,
Reason,
Importance,
Noofissues,
inserteddate
INTO #TABLE
FROM HistoricDatatest8 N
JOIN MasterTableTest S ON N.ID=S.ID
  

- 在哈希表中插入所需数据。

--drop table #table

   DECLARE @cols NVARCHAR (MAX)
SELECT @cols = COALESCE (@cols + ',[' + CONVERT(NVARCHAR, [inserteddate], 106) + ']', 
           '[' + CONVERT(NVARCHAR, [inserteddate], 106) + ']')
           FROM    (SELECT DISTINCT [inserteddate] FROM #TABLE) PV  
           ORDER BY [inserteddate]

           DECLARE @query NVARCHAR(MAX)
SET @query = '           
          SELECT * FROM 
         ( 
             SELECT * FROM #TABLE
         ) x
         PIVOT 
         (
             count(Noofissues)
             FOR [inserteddate] IN (' + @cols + ')
        ) p'
        EXEC SP_EXECUTESQL @query   

当前结果

current results image

预期结果:

expected results image

2 个答案:

答案 0 :(得分:0)

您的预期结果是什么?您当前的显示屏显示相同的当前和预期结果。

你期待: 日期|名称| ShortName |原因|重要性|问题数量| 05年7月6日| ATS | S |其他|高| 26 12月7日 - 16日| BTS | S1 |其他| LOW | 80

答案 1 :(得分:0)

经过大量的R&我得到了这个结果,可能对其他人有用。如果有任何优化的答案将不胜感激。

按ID从HistoricDatatest80订单中选择*     选择N.ID,N.Name,ShortName,Reason,Importance,Noofissues,inserteddate INTO #TABLE FROM HistoricDatatest80 N JOIN MasterTableTest80 S ON N.ID = S.ID

--drop table #table

   DECLARE @cols NVARCHAR (MAX)
SELECT @cols = COALESCE (@cols +',','')+ '['+DATEValue+']'
           FROM    (SELECT  DISTINCT (CONVERT(NVARCHAR, [inserteddate], 106)) AS DATEValue FROM HistoricDatatest80) PV  
           ORDER BY DATEValue
           print @cols
           DECLARE @query NVARCHAR(MAX)
SET @query = '           
          SELECT * FROM 
         ( 
             SELECT ShortName,Reason,Importance,Noofissues,(CONVERT(NVARCHAR, [inserteddate], 106)) AS DATEValue FROM #TABLE 
         ) x
         PIVOT 
         (
             sum(Noofissues)
             FOR [DATEValue] IN (' + @cols + ')

        ) p'    
        EXEC SP_EXECUTESQL @query   


   drop table #table