2017-04-13 63 views
0

我的查詢返回一個數據透視表,第一列(nummnth)包含01,02,03月份的月份,一月,二月,三月的文本值。問題在於排序爲01,03, 02而不是01,02,03。SQL Server樞軸訂購問題

我該如何解決這個問題?

查詢是:

select [nummnth] ,[mnth],[Business Fixed Score],[Business Fixed 
    Sessions],[Business Mobile Score],[Business Mobile Sessions],[Business 
    Merged Score],[Business Merged Sessions] from (Select [nummnth], 
    [Mnth],C.* from (
    SELECT [Service],nummnth,mnth,b.A2 as [User_Score],b.A2_Sessions as 
    [Sessions_Count] FROM [QTDB].[dbo].[QTD_BOX_BUS_MERGED_CP] as [b] where 
    YR=2017 
    and [service] = 'Business Fixed' and Agent='ANAME' 
    Union 
    SELECT [Service],nummnth,mnth,b.A2 as [User_Score],b.A2_Sessions as 
    [Sessions_Count] 
    FROM [QTDB].[dbo].[QTD_BOX_BUS_MERGED_CP] as [b] where YR=2017 and 
    [service] = 'Business Mobile' and Agent='ANAME' 
    UNION all 
    SELECT 'Business Merged' as [Service] ,nummnth,mnth,b.A2 as 
    [User_Score],b.A2_Sessions as [Sessions_Count] 
    FROM [QTDB].[dbo].[QTD_BOX_BUS_AGENT_MNTH_MERGED] as [b] where YR=2017 
    and Agent='ANAME') A 
    Cross Apply (Values (A.[Service]+' Score', 
    cast(A.[User_Score] as float)),(A.[Service]+' Sessions',cast(A. 
    [Sessions_Count] as float))) C (Item,Value)) R Pivot (
    sum(Value) For [Item] in ([Business Fixed Score], 
    [Business Fixed Sessions], 
    [Business Mobile Score],[Business Mobile Sessions], 
    [Business Merged Score],[Business Merged Sessions])) PV 

回答

1

在SQL-服務器沒有隱含的秩序!沒有,從來沒有...

你甚至不能說問題是,排序是01,03,02而不是01,02,03。下一次調用可能會返回不同的結果。

確保訂單的唯一方法是在最外面的查詢中輸入ORDER BY

只需添加ORDER BY [nummnth]作爲最後一行並檢查結果。

+0

我在查詢中的所有地方嘗試了ORDER BY [nummnth],除了在PV之後的最後。現在完美的工作..我覺得很愚蠢,但這是一個「編程到極端」的時期。 –

+0

@AndyL。我很高興,你可以解決你的問題。別介意,每個人都會不時地感到愚蠢: - D – Shnugo