Sql server聚合函数和GROUP BY子句错误

时间:2016-10-29 17:21:56

标签: sql sql-server aggregate-functions

我在下面有一个查询,它会比较暂存架构中stagingCabincrewStagingCockpitCrew列的数量,并将它们与等效的'DataCabinCrew''DataCockpitCrew'数据架构进行比较。

以下是查询和输出的结果:

WITH CTE AS
  (SELECT cd.*,
          c.*,
          DataFlight,
          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 = 1
   AND RowNumber = 1
   INNER JOIN
     (SELECT *,
             Carrier + CAST(FlightNumber AS VARCHAR) + Suffix AS DataFlight
      FROM Data.Leg) l ON c.LegKey = l.LegKey )
SELECT StagingFlight,
       sac.DepartureDate,
       sac.DepartureAirport,
       cte.DataFlight,
       cte.ScheduledDepartureDate,
       cte.ScheduledDepartureAirport,
       SUM(CASE
               WHEN sac.CREWTYPE = 'F' THEN 1
               ELSE 0
           END) AS StagingCabinCrew,
       SUM(CASE
               WHEN sac.CREWTYPE = 'C' THEN 1
               ELSE 0
           END) AS StagingCockpitCrew,
       SUM(CASE
               WHEN cte.CrewType = 'F' THEN 1
               ELSE 0
           END) AS DataCabinCrew,
       SUM(CASE
               WHEN cte.CrewType = 'C' THEN 1
               ELSE 0
           END) AS DataCockpitCrew
FROM
  (SELECT *,
          Airline + CAST(FlightNumber AS VARCHAR) + Suffix AS StagingFlight,
          ROW_NUMBER() OVER(PARTITION BY Airline + CAST(FlightNumber AS VARCHAR) + Suffix
                            ORDER BY UpdateId DESC) AS StageRowNumber
   FROM Staging.SabreAssignedCrew) sac
LEFT JOIN CTE cte ON StagingFlight = DataFlight
AND sac.DepartureDate = cte.ScheduledDepartureDate
AND sac.DepartureAirport = cte.ScheduledDepartureAirport
AND sac.CREWTYPE = cte.CrewType
WHERE MONTH(sac.DepartureDate) + YEAR(sac.DepartureDate) = MONTH(GETDATE()) + YEAR(GETDATE())
  AND StageRowNumber = 1 --AND cte.ScheduledDepartureDate IS NOT NULL
--AND cte.ScheduledDepartureAirport IS NOT NULL
GROUP BY StagingFlight,
         sac.DepartureDate,
         sac.DepartureAirport,
         cte.DataFlight,
         cte.ScheduledDepartureDate,
         cte.ScheduledDepartureAirport

结果是正确的,我需要做的就是在WHERE子句中添加StagingCabinCrew <> DataCabinCrew AND StagingCockpitCrew <> DataCockpitCrew

的条件

enter image description here

如果出现一行,那么我们在数据中发现了一个错误,我只需要帮助在WHERE子句中添加这个条件,因为WHERE子句中的列指的是SUM和CASE函数。我只需要帮助操作查询,以便我可以添加此WHERE子句

1 个答案:

答案 0 :(得分:1)

我猜你试图在同一个查询中使用别名。

CANT 执行此操作,因为别名无法在WHERE中识别。

SELECT  field1 + field2 as myField
FROM yourTable
WHERE myField > 3

您需要将其包含在子查询中

with cte2 as (

    SELECT  field1 + field2 as myField
    FROM yourTable
)
SELECT *
FROM cte2
WHERE myField > 3

或重复功能

    SELECT  field1 + field2 as myField
    FROM yourTable
    WHERE field1 + field2 > 3