如何将查询作为SQL中的变量嵌套?

时间:2015-02-25 04:27:07

标签: sql-server

显然,SQL不是我的第一语言,所以我需要一些可能微不足道的帮助。

我有以下查询:

SELECT Airports.IATA_Code,
    COUNT(*) AS Departures,
    (SELECT COUNT(*) FROM Flights WHERE DestinationAirportId = 63384) AS Arrivals, 
    SUM(Flights.Tickets) AS Tickets, 
    SUM(Flights.Fare * Flights.Tickets) As Revenue, 
    AVG(Flights.Demand) AS Demand 
FROM Flights
LEFT JOIN Airports
    ON Flights.OriginAirportId = Airports.Id
WHERE AnalysisId = 2
GROUP BY IATA_Code
ORDER BY Tickets DESC

此查询工作正常,但我需要将63384的硬编码ID替换为实际的机场ID。这将是Airports.Id但是当我尝试时,我收到以下错误:

Column 'Airports.Id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

解决!

只需要按照机场标识进行分组:

SELECT Airports.IATA_Code,
    COUNT(*) AS Departures,
    (SELECT COUNT(*) FROM Flights WHERE DestinationAirportId = Airports.Id) AS Arrivals, 
    SUM(Flights.Tickets) AS Tickets, 
    SUM(Flights.Fare * Flights.Tickets) As Revenue, 
    AVG(Flights.Demand) AS Demand 
FROM Flights
LEFT JOIN Airports
    ON Flights.OriginAirportId = Airports.Id
WHERE AnalysisId = 2
GROUP BY IATA_Code, Airports.Id     <---------------------------
ORDER BY Tickets DESC

1 个答案:

答案 0 :(得分:1)

在这里猜测......在OriginAirportId上应该有一个引用Airports.Id的FK。如果是这种情况,您可以inner join代替left join

另外,如果您选择CROSS APPLY,请尝试使用SELECT a.IATA_Code, COUNT(*) AS Departures, t.Arrivals, SUM(f.Tickets) AS Tickets, SUM(f.Fare * f.Tickets) As Revenue, AVG(f.Demand) AS Demand FROM Flights f INNER JOIN Airports a ON f.OriginAirportId = a.Id CROSS APPLY ( SELECT COUNT(*) AS Arrivals FROM Flights f1 WHERE f1.DestinationAirportId = a.Id) t WHERE AnalysisId = 2 GROUP BY IATA_Code, a.Id ORDER BY Tickets DESC

;WITH AirportDepartureCount AS (
    SELECT 
        OriginAirportId AS AirportId, 
        Count(*) AS DepartCount,
        SUM(f.Tickets) AS Tickets, 
        SUM(f.Fare * f.Tickets) As Revenue, 
        AVG(f.Demand) AS Demand
    FROM Flights
    GROUP BY OriginAirportId
), AirportArrivalCount AS (
    SELECT DestinationAirportId AS AirportId, COUNT(*) AS ArrivalCount
    FROM Flights
    GROUP BY DestinationAirportId
)
SELECT a.Id, a.IATA_Code, 
    COALESCE(depart.DepartCount,0) AS DepartCount, 
    COALESCE(arrival.ArrivalCount,0) AS ArrivalCount,
    COALESCE(depart.Tickets,0) AS Tickets,
    COALESCE(depart.Revenue,0) AS Revenue,
    COALESCE(depart.Demand,0) AS Demand
FROM Airports a
LEFT JOIN AirportDepartureCount depart
    ON a.Id = depart.AirportId
LEFT JOIN AirportArrivalCount arrival
    ON a.Id = arrival.AirportId
ORDER BY COALESCE(depart.Tickets,0) DESC

我没有对此代码进行测试,因此请仅将其用作参考。

或者你甚至可以试试这个......

{{1}}

此处的主要区别在于此代码适用于所有机场(即使是那些没有任何航班的机场)。在您的解决方案中,您忽略了任何没有任何离港航班的机场。也许这是设计的,但我认为为了完整起见我把它扔出去了;;)