我有3张桌子:
Trip Promotion Promotion Cost.
1 ---- M 1 --------- M
示例数据包括:
TripID TripName Date
XYZ123 Hawaii 09/06/09
YTU574 Japan 09/09/09
GHR752 US 11/07/09
PromotionID TripID Name
1 XYZ123 Poster
2 XYZ123 Brochure
3 GHR752 TV ad
CostID PromotionID Cost
1 1 $50
2 1 $100
3 1 $120
4 3 $2000
5 2 $500
我正在尝试构建这样的查询:
TripID Number of Promotions Total Cost
XYZ123 2 $770
GHR752 1 $2000
我拥有的是:
SELECT
Trip.TripID, Count(Trip.TripID) AS [Number Of Promotions], Sum(PromotionCost.Cost) AS SumOfCost
FROM
Trip
INNER JOIN
(Promotion
INNER JOIN
PromotionCost ON Promotion.PromotionID = PromotionCost.PromotionID
) ON Trip.TripID = Promotion.TripID
GROUP BY
Trip.TripID;
它给了我这样的东西:
TripID Number of Promotions Total Cost
XYZ123 4 $770
GHR752 1 $2000
我不确定为什么促销数量会像第一个(XYZ123)那样混乱。似乎JOIN以某种方式影响它,因为如果我使用它:
SELECT
Trip.TripID, Count(Trip.TripID) AS [Number Of Promotions],
FROM
Trip
INNER JOIN
Promotion ON Trip.TripID = Promotion.TripID
GROUP BY
Trip.TripID;
它为我提供了正确的促销数量,仅为2个。
答案 0 :(得分:2)
您可以在子查询中累计每个促销的费用。这样,每次促销只获得一行,COUNT用于计算每次促销的促销数量。例如:
select
t.TripId
, count(p.PromotionId) as [Number of Promotions]
, sum(pc.PromotionCost) as [Total Cost]
from trip t
left join promotions p on p.TripId = t.TripId
left join (
select
PromotionId
, PromotionCost = sum(cost)
from Promotions
group by PromotionId
) pc on pc.PromotionId = p.PromotionId
group by t.TripId
如果MS Access不允许子查询,您可以将子查询存储在视图中,然后加入该查询。
答案 1 :(得分:1)
您可以尝试使用COUNT(DISTINCT)
SELECT Trip.TripID, Count(DISTINCT Promotion.PromotionID) AS [Number Of Promotions],
Sum(PromotionCost.Cost) AS SumOfCost
FROM Trip INNER JOIN Promotion ON Trip.TripID = Promotion.TripID
INNER JOIN PromotionCost ON Promotion.PromotionID = PromotionCost.PromotionID
GROUP BY Trip.TripID;
正在发生的事情是,默认情况下,COUNT()
计算所有连接完成后生成的行数。 TripID XYZ123有四个促销费用,因此有四行,即使TripId在这四行中多次出现。
如果您在没有GROUP BY的情况下尝试类似的查询,则更容易可视化:
SELECT Trip.TripID, Promotion.PromotionID, PromotionCost.Cost
FROM Trip INNER JOIN Promotion ON Trip.TripID = Promotion.TripID
INNER JOIN PromotionCost ON Promotion.PromotionID = PromotionCost.PromotionID;
您将看到XYZ123的四行(具有重复的PromotionID值)和GHR752的一行。
重新评论MS Access不支持COUNT(DISTINCT)
:如果是这种情况,则不应在单个查询中执行此操作。在两个查询中执行:
SELECT Trip.TripID, SUM(PromotionCost.Cost) AS SumOfCost
FROM Trip INNER JOIN Promotion ON Trip.TripID = Promotion.TripID
INNER JOIN PromotionCost ON Promotion.PromotionID = PromotionCost.PromotionID
GROUP BY Trip.TripID;
SELECT Trip.TripID, Count(Promotion.PromotionID) AS [Number Of Promotions]
FROM Trip INNER JOIN Promotion ON Trip.TripID = Promotion.TripID
GROUP BY Trip.TripID;
替代方案是一个使用子查询的非常复杂的解决方案,在Microsoft的这篇文章中有描述:
http://blogs.msdn.com/access/archive/2007/09/19/writing-a-count-distinct-query-in-access.aspx
答案 2 :(得分:0)
不是您的问题的答案,而是一个有用的建议(我希望):使用SQL Server Management Studio的可视化设计器将您的查询转换为视图,并检查生成的SQL代码。您不必实际保留和使用生成的视图,但这是一个通过示例学习的好方法。每当我遇到复杂的查询时,我就会这样做。
修改即可。惭愧我,我不读标签:问题是MS-Access相关,而不是SQL Server相关。无论如何,我认为我的建议仍然有效,因为概念学习是关注点,因为SQL语法是相似的。