如何在CTE中添加计数/总和和分组

时间:2016-10-29 11:10:02

标签: sql sql-server

只是在飞行高度显示一行并显示该航班上有多少机组人员的问题。

我想更改输出,因此它只会在飞行级别显示一条记录,并会显示另外两列。一列(机组螺旋)是具有'CREWTYPE' = 'F'的机组人员,另一列(cockpitcrew)是具有''CREWTYPE'='C'的机组成员。

因此查询结果应如下所示:

Flight  DepartureDate DepartureAirport  CREWBASE  CockpitCrew CabinCrew
LS361    2016-05-19     BFS                BFS        0            3

我可以帮助调整下面的查询:

WITH CTE AS (
SELECT cd.*, c.*, l.Carrier, l.FlightNumber, l.Suffix, l.ScheduledDepartureDate, l.ScheduledDepartureAirport
FROM 
(SELECT *, ROW_NUMBER() OVER(PARTITION BY LegKey ORDER BY UpdateID DESC) AS RowNumber FROM Data.Crew) c
INNER JOIN 
Data.CrewDetail cd
ON c.UpdateID = cd.CrewUpdateID
AND cd.IsPassive = 0
AND RowNumber = 1
INNER JOIN 
Data.Leg l
ON c.LegKey = l.LegKey
)
SELECT
    sac.Airline + CAST(sac.FlightNumber AS VARCHAR) + sac.Suffix AS Flight
,   sac.DepartureDate
,   sac.DepartureAirport
,   sac.CREWBASE
,   sac.CREWTYPE
,   sac.EMPNO
,   sac.FIRSTNAME
,   sac.LASTNAME
,   sac.SEX
FROM 
Staging.SabreAssignedCrew sac
LEFT JOIN CTE cte
ON sac.Airline + CAST(sac.FlightNumber AS VARCHAR) + sac.Suffix = cte.Carrier + CAST(cte.FlightNumber AS VARCHAR) + cte.Suffix
AND sac.DepartureDate = cte.ScheduledDepartureDate

2 个答案:

答案 0 :(得分:2)

请你试试。

  SELECT    Flight,
            DepartureDate,
            DepartureAirport,  
            CREWBASE,
            SUM(CASE WHEN CREWTYPE = 'F' THEN 1 ELSE 0 END) AS CabinCrew ,
            SUM(CASE WHEN CREWTYPE = 'C' THEN 1 ELSE 0 END) AS CockpitCrew
      FROM  @Table
    GROUP BY Flight, DepartureDate, DepartureAirport, CREWBASE

答案 1 :(得分:1)

请试试这个:

select Flight, DepartureDate, DepartureAirport,CREWBASE,
count(case when CREWTYPE='F' then 1 end ) as CabinCrew,count(case when CREWTYPE='C' then 1 end ) as CockpitCrew 
from Staging.SabreAssignedCrew
group by Flight, DepartureDate, DepartureAirport,CREWBASE