我试图制定一个SQL查询来计算人数的差异"到达"和#34;离开"按城市和日期分组。
TravelerID ArrivalDate DepartureDate City
1 2015-10-01 2015-10-03 New York
2 2015-10-02 2015-10-03 New York
3 2015-10-02 2015-10-04 Chicago
4 2015-10-01 2015-10-02 Chicago
我希望得到一张看起来像
的桌子NumOfTravelers Date City
1 2015-10-01 New York
1 2015-10-02 New York
-2 2015-10-03 New York
1 2015-10-01 Chicago
0 2015-10-02 Chicago
-1 2015-10-04 Chicago
NumOfTravelers的正数表示在该特定日期有更多人抵达该城市。 NumOfTravelers的负数表示在该特定日期有更多人离开该城市。
在尝试分解此SQL查询时,我已尝试
SELECT COUNT(TravelerID) as NumTravelersArrivng, ArrivalDate, City FROM TravelTable GROUP BY ArrivalDate, City;
SELECT COUNT(TravelerID) as NumTravelersDeparting, DepartureDate, City FROM TravelTable GROUP BY DepartureDate, City;
我试图获得" NumTravelersArriving" - " NumTravelersDeparting"到表示"旅行者吞吐量的列中#34;按城市和日期分组。
我对此感到非常难过。我正在使用SQL Server,并且在使用表别名和列别名时遇到了令人沮丧的时间。
答案 0 :(得分:1)
试试这个:
SELECT *
FROM (
SELECT City, ArrivalDate As Date, COUNT(TravelerID) As NumOfTravelers
FROM TravelTable
GROUP BY City, ArrivalDate
) a
FULL JOIN (
SELECT City, DepartureDate As Date, COUNT(TravelerID) * -1 As NumOfTravelers
FROM TravelTable
GROUP BY City, DepartureDate
) b ON b.City = a.City AND b.Date = a.Date