2

我正在尝试创建两列:IntlAir 和 DomesticAir。我的数据中有一个名为 的布尔列International,IntlAirPenalty + SellingFareInternationalis时TRUE返回,DomAir 在何时返回该总和International = FALSE

我想按月显示每个 DK 的金额。

我的代码是:

SELECT data.PostingMonth, data.DK_Number
     , (SELECT sum(data.Penalty + data.SellingFare)
        FROM data
        WHERE data.International = TRUE) AS IntlAir
     , (SELECT sum(data.Penalty + data.SellingFare)
        FROM data
        WHERE data.International = FALSE) AS DomesticAir
FROM data
GROUP BY data.PostingMonth, data.DK_Number
ORDER BY data.PostingMonth;

然而,输出给了我所有 dks 和所有月份的总和,并将这个值放入每一行。

有人可以告诉我我做错了什么吗?

4

2 回答 2

1

也许这就是你所需要的:

SELECT
    PostingMonth,
    DK_Number,
    SUM((Penalty + SellingFare) * IIf(International, 1, 0)) AS IntlAir,
    SUM((Penalty + SellingFare) * IIf(International, 0, 1)) AS DomAir
FROM [data]
GROUP BY PostingMonth, DK_Number

对于测试数据...

PostingMonth    DK_Number   International   Penalty SellingFare
------------    ---------   -------------   ------- -----------
1               1           False           $10.00  $100.00
1               1           True            $20.00  $200.00
2               1           False           $30.00  $300.00
1               2           False           $40.00  $400.00
1               2           False           $50.00  $500.00
1               2           True            $60.00  $600.00

...上面的查询返回

PostingMonth    DK_Number   IntlAir DomAir
------------    ---------   ------- -------
1               1           $220.00 $110.00
1               2           $660.00 $990.00
2               1           $0.00   $330.00
于 2013-09-13T01:00:01.543 回答
0

有几种方法可以做到这一点,尽管您选择的不是其中之一

永远不确定访问在 sql 方面的位置,但如果您创建一个执行此操作的查询并将其称为 queryAirTotal 或类似的

SELECT PostingMonth, DK_Number, International, sum(Penalty + SellingFare) as AirTotal
FROM data GROUP BY PostingMonth,DK_Number,International

这将按月、dk 和类型给出你的总数,然后你可以做

Select t1.PostingMonth,t1.DK_Number,t1.AirTotal as IntlAir, t2.Total as DomesticAir
From queryAirTotal t1
Left Join queryAirTotal t2 
On t1.PostingMonth = t2.PostingMonth and t1.DK_Number = t2.DK_Number
Where t1.International = TRUE and t2.International = FALSE

虽然这将错过只有国内航空而没有国际航空的月份/DK。您可以使用完整的外部连接对其进行排序,我相信访问也很困难。

你可以通过联盟来解决这个问题

Select t1.PostingMonth,t1.DK_Number,t1.AirTotal as IntlAir, t2.Total as DomesticAir
From queryAirTotal t1
Left Join queryAirTotal t2 
On t1.PostingMonth = t2.PostingMonth and t1.DK_Number = t2.DK_Number
Where t1.International = TRUE and t2.International = FALSE
Union
Select t1.PostingMonth,t1.DK_Number,t1.AirTotal as IntlAir, t2.Total as DomesticAir
From queryAirTotal t1
Left Join queryAirTotal t2 
On t2.PostingMonth = t1.PostingMonth and t2.DK_Number = t1.DK_Number
Where t1.International = TRUE and t2.International = FALSE
于 2013-09-12T20:28:47.860 回答