3

我在查詢中有以下輸出。如何在不彙總列的情況下調整sql數據

SKILL            LEVEL   SCORERANGE 
----------------------------------------------------------------------------- 
Stunts            LOW   0.0 - 4.0 
Stunts            MED   3.0 - 7.0 
Stunts            HI    6.0 - 10.0 
Pyramids           LOW   0.0 - 4.0 
Pyramids           MED   3.0 - 7.0 
Pyramids           HI    6.0 - 10.0 
Tosses            LOW   0.0 - 4.0 
Tosses            MED   3.0 - 7.0 
Tosses            HI    6.0 - 10.0 
Standing Tumbling         LOW   0.0 - 4.0 
Standing Tumbling         MED   3.0 - 7.0 
Standing Tumbling         HI    6.0 - 10.0 
Running Tumbling         LOW   0.0 - 4.0 
Running Tumbling         MED   3.0 - 7.0 
Running Tumbling         HI    6.0 - 10.0 
Jumps            LOW   0.0 - 4.0 
Jumps            MED   3.0 - 7.0 

我想在不彙總任何東西的情況下將這些數據排除在外。所以,我想只顯示一個每個技能行和樞軸的水平,這樣的結果......

SKILL            LOWRANGE  MEDRANGE  HIRANGE 
Stunts            0.0 - 4.0  3.0 - 7.0  6.0 - 10.0 
Pyramids           0.0 - 4.0  3.0 - 7.0  6.0 - 10.0 
Tosses            0.0 - 4.0  3.0 - 7.0  6.0 - 10.0 
Standing Tumbling         0.0 - 4.0  3.0 - 7.0  6.0 - 10.0 
Running Tumbling         0.0 - 4.0  3.0 - 7.0  6.0 - 10.0 
... 

我有基本的支點語法的一個很好的理解,但我與這一個,因爲掙扎結果集中沒有任何要聚合的內容。

爲了給你的東西來嘗試解決我...

SELECT SKILL, LOWRANGE, MEDRANGE, HIRANGE 
FROM (SELECT SKILL, [LEVEL], SCORERANGE FROM ScoreRanges) ps 
PIVOT 
    (
     MAX(SCORERANGE) --THIS IS PROBABLY WRONG 
     FOR SCORERANGE IN 
     (
      --SOMETHING GOES HERE 
     ) 
    ) as pvt 

感謝您的幫助。

賽斯

回答

4

當你知道你將只有每SKILL, LEVEL組合1列,您可以使用MaxMin

SELECT SKILL, [LOW] LOWRANGE, [MED] MEDRANGE, [HI] HIRANGE 
FROM (SELECT SKILL, [LEVEL], SCORERANGE FROM ScoreRanges) ps 
PIVOT (
     MAX(SCORERANGE) 
     FOR LEVEL IN ([LOW], [MED], [HI]) 
    ) as pvt 
1

你幾乎得到它的權利

SELECT SKILL, LOW as LOWRANGE, MED as MEDRANGE, HI as HIRANGE 
FROM (SELECT SKILL, [LEVEL], SCORERANGE FROM ScoreRanges) ps 
PIVOT 
    (
     MAX(SCORERANGE) 
     FOR [LEVEL] IN 
     (
      [LO], [HIGH], [MED] 
     ) 
    ) as pvt 

下面是一個例子你可以在Adventureworks數據庫中運行,所以你可以玩這個也看看如何PIVOT工作

SELECT City, F AS Females, M AS Males 
FROM(
SELECT Gender,City 
FROM HumanResources.Employee AS e 
    INNER join HumanResources.EmployeeAddress AS ea 
    ON e.EmployeeID = ea.EmployeeID 
    INNER join Person.Address AS p 
    ON ea.AddressID = p.AddressID 
    ) AS pivTemp 
PIVOT 
( COUNT(Gender) 
    FOR Gender IN (F,M) 
) AS pivTable 

我也有反璞歸真PIVOT例子在這裏:Three different ways of populating variables with configuration values in SQL Server

相關問題