我用以下查询回答了关于 SO 的问题之一:
SELECT s.address
FROM shop s
JOIN visit v ON s.shopid = v.shopid
JOIN customer c ON v.customerid = c.customerid
WHERE c.cname = 'John'
GROUP BY
s.address
, c.customerid
HAVING COUNT(*) > 1
这很好用,但如果给定商店有 2 个或多个 John's 满足查询条件,则会返回重复的地址,因此我修改了答案:
SELECT DISTINCT a.address
FROM
(
SELECT s.address
FROM shop s
JOIN visit v ON s.shopid = v.shopid
JOIN customer c ON v.customerid = c.customerid
WHERE c.cname = 'John'
GROUP BY
s.address
, c.customerid
HAVING COUNT(*) > 1
) a
现在我的问题是:是否可以在评估聚合表达式时先实现分组,然后再在单个查询中进行选择?