我正在尝试创建两列:IntlAir和DomesticAir。我的数据中有一个名为International
的布尔列,当Penalty + SellingFare
为International
时,IntlAir会返回TRUE
,而International = FALSE
时,DomAir会返回该总和。
我想按月显示每个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和所有月份的总和,并将此值放入每一行。
有人能告诉我我做错了吗?
答案 0 :(得分: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
答案 1 :(得分: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