【问题标题】:pivot with dynamic date columns in SqlServer 2012 & MySQL在 SqlServer 2012 和 MySQL 中使用动态日期列进行数据透视
【发布时间】:2017-11-12 12:29:14
【问题描述】:

我有以下数据。

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 数据库中有相同的数据。

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

【问题讨论】:

    标签: mysql sql sql-server-2012 pivot


    【解决方案1】:
    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);
    

    退货

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

    【讨论】:

    • 非常适合。
    • @ChakradharM 很高兴它有帮助
    猜你喜欢
    • 2018-04-21
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-06
    • 1970-01-01
    • 2013-05-15
    • 2017-05-27
    相关资源
    最近更新 更多