简体   繁体   English

SQL Pivot 上动态日期范围

[英]SQL Pivot on Dynamic Date Range

I'm attempting to pivot counts on dates in SSMS with a dynamic date range (previous 90 days), but my dates are out of order in the results.我正在尝试 pivot 计数具有动态日期范围(前 90 天)的 SSMS 中的日期,但我的日期在结果中是无序的。 Is there a way to put an ORDER BY in this query?有没有办法在这个查询中放置一个 ORDER BY ? Or, does someone have a better way to pivot on a dynamic date range?或者,有人在动态日期范围内有更好的方法来 pivot 吗?

declare @cols as nvarchar(max);
declare @query as nvarchar(max); 

select @cols = stuff((select distinct 
                             ',' + quotename(ColumnDate) 
                        from 
                             [Database].[Schema].[ExampleTable] as et
                         for 
                             xml path(''), type).value('.', 'nvarchar(max)'), 1, 1, '');

select @query = 'select *
                   from 
                        (select et.Place                   
                                ,et.ColumnDate
                                ,et.ValueToAggregate
                           from 
                                [Database].[Schema].[ExampleTable] as et) as t 
                  pivot   
                        (count(ValueToAggregate) 
                         for ColumnDate in( ' + @cols + ')' + ')  as p; ';
                        
execute(@query);




The dates in my results are out of order...

Place               |3/25/2021  |4/19/2021  |2/21/2021  |3/22/2021  |2/14/2021  |2/11/2021
Test_Facility_1     |6          |5          |0          |2          |0          |3
Test_Facility_2     |1          |0          |0          |2          |2          |2
Test_Facility_3     |0          |1          |0          |1          |1          |2
Test_Facility_4     |124        |111        |85         |83         |95         |97

You can use ORDER BY in your first SELECT statement between the FROM and the FOR XML .您可以在FROMFOR XML之间的第一个 SELECT 语句中使用ORDER BY However, exactly which expression to use in the order by may depend on the data type of column ColumnDate .但是,在 order by 中确切使用哪个表达式可能取决于ColumnDate列的数据类型。 If it is a date column, then you can just use如果它是一个日期列,那么你可以使用

ORDER BY ColumnDate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM