SQL 以动态日期范围为轴心

SQL Pivot on Dynamic Date Range

我正尝试在 SSMS 中使用动态日期范围(之前 90 天)对日期进行计数,但我的日期在结果中是乱序的。有没有办法在此查询中放置 ORDER BY?或者,有人有更好的方法来调整动态日期范围吗?

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

您可以在 FROMFOR XML 之间的第一个 SELECT 语句中使用 ORDER BY。但是,在 order by 中确切使用哪个表达式可能取决于列 ColumnDate 的数据类型。如果它是一个日期列,那么你可以使用

ORDER BY ColumnDate