我正在努力理解如何使用pivot操作符来转置表但我无法弄明白。任何帮助都会很棒。这是我需要转置的查询。
SELECT
sum(delayCarrier>0) AS 'Carrier Delay',
sum(delayWeather>0) AS 'Weather Delay',
sum(delayTraffic>0) AS 'Air Traffic Delay',
sum(delaySecurity>0) AS 'Security Delay'
FROM flights
我需要它阅读:
'TypeOfDelay','Frequency'
-------------------------
Carrier Delay | 32093
Weather Delay | 4887
Air Traffic Delay | 40730
Security Delay | 215
抱歉,我知道这个问题已经被问了很多,我看了很多,但我似乎无法获得任何直觉。提前谢谢。
答案 0 :(得分:1)
这是一个查询,它可以为您提供所需的输出,但我不能说老实说这是一个支点,或者它很漂亮。
SELECT 'Carrier Delay' AS TypeOfDelay, SUM(delayCarrier > 0) AS Frequency
FROM flights
UNION ALL
SELECT 'Weather Delay' AS TypeOfDelay, SUM(delayWeather > 0) AS Frequency
FROM flights
UNION ALL
SELECT 'Air Traffic Delay' AS TypeOfDelay, SUM(delayTraffic > 0) AS Frequency
FROM flights
UNION ALL
SELECT 'Security Delay' AS TypeOfDelay, SUM(delaySecurity > 0) AS Frequency
FROM flights