我正在尝试计算前往每个目的地的乘客人数。这是一些示例代码,如果有帮助的话。
DDL:
CREATE TABLE #PAX
(
FLIGHT_NO INT,
SEG INT,
DEP VARCHAR(3),
ARR VARCHAR(3),
First_Class INT,
Economy INT
)
DML:
INSERT INTO #PAX(FLIGHT_NO, SEG, DEP, ARR, First_Class, Economy)
SELECT 220, 1, 'STL', 'JFK', 11, 166
UNION ALL
SELECT 220, 2, 'STL', 'DXB', 13, 21
UNION ALL
SELECT 220, 3, 'JFK', 'DXB', 11, 150;
我想知道有多少乘客飞往 JFK 和 DXB。
预期结果:
SELECT 'STL', 'JFK', 24, 187
UNION ALL
SELECT 'JFK', 'DXB', 24, 171
到目前为止我的尝试:
WITH CTE1 AS
(
SELECT DEP, SUM(First_Class) AS First_Class, SUM(Economy) AS Economy FROM #PAX GROUP BY DEP HAVING COUNT(DEP) > 1
),
LEG2 AS
(
SELECT ARR, SUM(First_Class) AS First_Class, SUM(Economy) AS Economy FROM #PAX GROUP BY ARR HAVING COUNT(ARR) > 1
)
SELECT #PAX.DEP, #PAX.ARR, CTE1.DEP, LEG2.ARR,
SUM(CTE1.First_Class) AS First_Class, SUM(CTE1.Economy) AS Economy
,SUM(LEG2.First_Class) AS First_Class, SUM(LEG2.Economy) AS Economy
FROM #PAX LEFT OUTER JOIN CTE1 ON #PAX.DEP = CTE1.DEP
LEFT OUTER JOIN LEG2 ON #PAX.ARR = LEG2.ARR
GROUP BY #PAX.DEP, #PAX.ARR
, CTE1.DEP, LEG2.ARR