注意:我浏览了类似的问题,但他们没有回答我的问题。
为了练习SQL,我在MS Access中创建了一个测试数据库。它存储有关汽车商店业务的信息。布局如下:
我希望列出(由他们分组)汽车使用最经常为给定品牌购买/订购的服务。我不知道如何在这里使用ORDER BY
条款。 SO:每个品牌只应展示一次,最常购买的服务。
例:
保时捷|换油
福特|轮胎更换
雪佛兰|制动液更换
等
我想我应该以某种方式筑巢,但我不知道如何做到这一点。
我能够构建以下查询,该列表将列出所有汽车服务关系:
SELECT cars.Make, services.[Service name]
FROM (repairs
INNER JOIN cars ON cars.[Car number] = repairs.[Car number])
INNER JOIN services ON services.ID = repairs.[Service ID]
GROUP BY cars.Make, services.[Service name];
如何正确构建此查询,如上所述?
答案 0 :(得分:1)
你可以尝试这个查询,它在子查询中使用MAX和COUNT吗?
SELECT sub1.make, sub1.[Service name]
FROM (
SELECT cars.Make, services.[Service name], COUNT(*) as COUNTREPAIR
FROM (repairs
INNER JOIN cars ON cars.[Car number] = repairs.[Car number])
INNER JOIN services ON services.ID = repairs.[Service ID]
GROUP BY cars.Make, services.[Service name]
) sub1
INNER JOIN
(SELECT sub2.make, MAX(COUNTREPAIR) as MAXCOUNT
FROM
(
SELECT cars.Make, services.[Service name], COUNT(*) as COUNTREPAIR
FROM (repairs
INNER JOIN cars ON cars.[Car number] = repairs.[Car number])
INNER JOIN services ON services.ID = repairs.[Service ID]
GROUP BY cars.Make, services.[Service name]
) sub2
GROUP BY sub2.Make
) sub3
ON sub1.COUNTREPAIR = sub3.MAXCOUNT
AND sub1.MAKE = sub3.MAKE;
我整合了一个Access数据库和一些模仿你的虚拟数据,所以希望它能为你提供所需的结果。
如果您想要这些服务的COUNT,可以在第一行的末尾添加“sub1.COUNTREPAIR”。