如何在sql中的pivot列中进行升序排序

时间:2018-06-14 12:54:43

标签: sql-server

我需要在每个系统中获取每小时的报告。我使用pivot获取所有数据。但是在我的专栏中没有按升序排序。

我的代码在这里:

DECLARE @cols  AS NVARCHAR(MAX)='';
DECLARE @query AS NVARCHAR(MAX)='';

SELECT @cols = @cols + QUOTENAME(hour) + ',' FROM (select distinct DATEPART(hh, BillDate) AS hour from Bill_Entry WHERE BillDate >= '6/10/2018 12:00:00' AND BillDate < '7/10/2018 12:00:00' ) as tmp
select @cols = substring(@cols, 0, len(@cols)) --trim "," at end

set @query = 
'SELECT * from 
(
    SELECT Remarks, DATEPART(hh, BillDate) AS hour, sum(cast(GrandTotal as int)) as Total
FROM Bill_Entry  WHERE BillDate >=  ''6/10/2018 12:00:00''  AND BillDate <=  ''7/10/2018 12:00:00''

GROUP BY DATEPART(hh, BillDate),Remarks 

) src
pivot 
(
    max(Total) for hour in (' + @cols + ')
) piv order by Len(Remarks), Remarks'

execute(@query)

我的输出是这样的:

enter image description here

这里我的专栏没有按升序排列。 我需要像

这样的列

8 9 10 11 12 13 14 15 16 17 18 ......

1 个答案:

答案 0 :(得分:1)

您应该进行以下更改

DECLARE @cols  AS NVARCHAR(MAX)='';
DECLARE @query AS NVARCHAR(MAX)='';

SELECT @cols = @cols + 
            QUOTENAME(hour) + 
            ',' 
            FROM (
            select distinct DATEPART(hh, BillDate) AS hour 
            from Bill_Entry 
            WHERE BillDate >= '6/10/2018 12:00:00' 
            AND BillDate < '7/10/2018 12:00:00' 
            ) as tmp
            ORDER BY DATEPART(hh, BillDate) ASC
            -- the above order by line will solve your issue
select @cols = substring(@cols, 0, len(@cols)) --trim "," at end

set @query = 
'SELECT * from 
(
    SELECT Remarks, DATEPART(hh, BillDate) AS hour, sum(cast(GrandTotal as int)) as Total
FROM Bill_Entry  WHERE BillDate >=  ''6/10/2018 12:00:00''  AND BillDate <=  ''7/10/2018 12:00:00''

GROUP BY DATEPART(hh, BillDate),Remarks 

) src
pivot 
(
    max(Total) for hour in (' + @cols + ')
) piv order by Len(Remarks), Remarks'

execute(@query)