[英]TSQL PIVOT MULTIPLE COLUMNS
我有下表,但不確定是否可以旋轉它並保留所有標簽。
RATIO RESULT SCORE GRADE
Current Ratio 1.294 60 Good
Gearing Ratio 0.3384 70 Good
Performance Ratio 0.0427 50 Satisfactory
TOTAL NULL 180 Good
我會承認對樞軸的使用不是很好,因此經過幾次嘗試導致此輸出:
SELECT 'RESULT' AS 'Ratio'
,[Current Ratio] AS 'Current Ratio'
,[Gearing Ratio] AS 'Gearing Ratio'
,[Performance Ratio] AS 'Performance Ratio'
,[TOTAL] AS 'TOTAL'
FROM
(
SELECT RATIO, RESULT
FROM GRAND_TOTALS
) AS SREC
PIVOT
(
MAX(RESULT)
FOR RATIO IN ([Current Ratio],[Gearing Ratio], [Performance Ratio], [TOTAL])
) AS PVT
結果如下:
Ratio Current Ratio Gearing Ratio Performance Ratio
Result 1.294 0.3384 0.0427
我承認在下一步該怎么做才能產生所需的結果時感到很沮喪:
Ratio Current Ratio Gearing Ratio Performance Ratio TOTAL
Result 1.294 0.3384 0.0427 NULL
Score 60 70 50 180
Grade Good Good Satisfactory Good
由於您想透視數據的多列,因此我首先建議不要透視result
, score
和grade
列,這樣就不會有多列,但會有多行。
根據您的SQL Server版本,您可以使用UNPIVOT函數或CROSS APPLY。 取消數據透視的語法類似於:
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
請參閱帶有演示的SQL Fiddle 。 一旦數據被取消透視,就可以應用PIVOT功能:
select ratio = col,
[current ratio], [gearing ratio], [performance ratio], total
from
(
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
) d
pivot
(
max(value)
for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;
請參閱帶有演示的SQL Fiddle 。 這將為您提供結果:
| RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO | TOTAL |
|--------|---------------|---------------|-------------------|-----------|
| grade | Good | Good | Satisfactory | Good |
| result | 1.29400 | 0.33840 | 0.04270 | (null) |
| score | 60.00000 | 70.00000 | 50.00000 | 180.00000 |
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.