如何在数据透视SQL Server中订购日期

时间:2019-02-23 12:20:58

标签: sql-server

数据

NOINDUK|PRIODE | TGL    
100101  12019   1/21/2019
100101  12019   1/22/2019
100101  12019   1/23/2019
100101  12019   1/24/2019
100101  12019   1/25/2019
100101  12019   1/26/2019
100101  12019   1/27/2019
100101  12019   1/28/2019
100101  12019   1/29/2019
100101  12019   1/30/2019
100101  12019   1/31/2019
100101  12019   2/1/2019
100101  12019   2/2/2019
100101  12019   2/3/2019
100101  12019   2/4/2019
100101  12019   2/5/2019
100101  12019   2/6/2019
100101  12019   2/7/2019
100101  12019   2/8/2019
100101  12019   2/9/2019
100101  12019   2/10/2019
100101  12019   2/11/2019
100101  12019   2/12/2019
100101  12019   2/13/2019
100101  12019   2/14/2019
100101  12019   2/15/2019
100101  12019   2/16/2019
100101  12019   2/17/2019
100101  12019   2/18/2019
100101  12019   2/19/2019
100101  12019   2/20/2019
100102  12019   2/19/2019
100102  12019   2/20/2019
100103  12019   2/19/2019
100103  12019   2/20/2019

如何在数据透视中通过tgl排序,我在sql中有这样的代码。

ALTER PROCEDURE [dbo].[procshift]

@priode nvarchar(6),

@cols   nvarchar(max)='' ,

@query  nvarchar(max)=''

AS

BEGIN

select @cols = STUFF((SELECT distinct ',' + QUOTENAME((tgl)) 

                    from tblabsen where priode = @priode 

            FOR XML PATH(''), TYPE

            ).value('.', 'NVARCHAR(MAX)') 

        ,1,1,'')


set @query = 'SELECT [no_induk],priode, ' + @cols + ' 
            from 
            (
              select [no_induk], tgl, kodealasan,priode
              from tblabsen where priode = '''+@priode+'''    
            ) x
            pivot 
            (
                max(kodealasan)
                for [tgl] in (' + @cols + ')
            ) p '       
END
execute sp_executesql @query;


如果我执行此操作,则会得到这样的结果

no_induk priode 1-Feb-19 2-Feb-19 3-Feb-19    
100101   12019   P         P       P

显示数据不排序,如何通过tgl进行查询

no_induk priode 21-jan-19 22-jan-19 23-jan-19     
100101   12019   P         P         P

2 个答案:

答案 0 :(得分:0)

只需在生成列的语句中添加ORDER BY

SET @cols = STUFF((SELECT ',' + QUOTENAME((tgl)) 
                   FROM tblabsen
                   WHERE priode = @priode 
                   GROUP BY tgl
                   ORDER BY tgl ASC
                   FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'');

我还建议对动态语句进行参数化。将where priode = '''+@priode+'''更改为

WHERE priode = @priode

,然后将您的sp_executesql更改为:

EXEC sp_executesql @query, N'@priode nvarchar(6)', @priode = @priode;

编辑,我刚刚注意到,为什么@cols@query在这里是参数?从参数列表中删除它们,然后DECLARE在您的SP中。

答案 1 :(得分:0)

您可以尝试下面的代码以升序获取所有日期列。

DECLARE @cols   nvarchar(max)='' 
    SELECT @cols = COALESCE(@cols + '[', '')+ FORMAT(tgl,'dd-MMM-yyyy')+'],'
      FROM tblabsen
      GROUP BY date
      ORDER BY date 
       IF (LEN(@cols)>1)
      BEGIN 
      Set  @cols = STUFF(@cols, LEN(@cols), 1, '')
      END