在 Sql Server 2012 中使用动态日期列进行数据透视 & MySQL

pivot with dynamic date columns in SqlServer 2012 & MySQL

我有以下数据。

create table #temp
(
 date date primary key
 ,registrations int not null default(0)
 ,orders int not null default(0)
)

insert into #temp
(
date ,
registrations
,orders
)values('2017-05-01',30,40),('2017-05-02',60,30),('2017-05-03',109,98)

select * from #temp

对于每个日期,数据都会不断添加。这是非常有活力的。如果@from_dt 和@to_dt 作为参数提供,是否仍然可以使用动态日期来转换数据。输出应如下所示。

                 2017-05-01       2017-05-02        2017-05-03
registrations        30                 60              109
orders               40                 30              98

我在 SQLServer 和 MySQL 数据库中有相同的数据。

感谢任何帮助。提前致谢。

Declare @Date1 date = '2017-05-01'
Declare @Date2 date = '2017-05-02'  -- Notice only Two Days


Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName([Date]) From #temp Where [Date] between @Date1 and @Date2  Order by 1 For XML Path('')),1,1,'') 
Select  @SQL = '
Select *
From (
        select [Date]
              ,B.*
         From #temp
         Cross Apply (values (''Orders'',orders)
                            ,(''Registrations'',registrations)
                     ) B(Item,Value)
         Where [Date] between '''+convert(varchar(10),@Date1,120)+''' and '''++convert(varchar(10),@Date2,120)+'''
     ) A
 Pivot (sum(Value) For [Date] in (' + @SQL + ') ) p'
Exec(@SQL);

Returns

Item            2017-05-01  2017-05-02
Orders          40          30
Registrations   30          60