我正在尝试创建一个视图,我可以在其中查看租用者名称以及他们从事务表中访问过多少次。在第一个例子中,我不断收到错误"子查询返回超过1行"。第二个例子给了我租房者ID和访问时间。
SELECT first_name, last_name,
(SELECT COUNT(renter_id)
FROM transactions
GROUP BY renter_id
) AS visited
FROM renters
WHERE renter_id IN (SELECT renter_id
FROM transactions
GROUP BY renter_id
having COUNT(renter_id) > 2
);
SELECT renter_id, COUNT(renter_id) AS visited
FROM transactions
GROUP BY renter_id
having COUNT(renter_id) > 2;
答案 0 :(得分:0)
您正在寻找JOIN
。查询如下所示:
SELECT r.first_name, r.last_name, COUNT(*) AS num_visits
FROM transactions t JOIN
renters r
ON t.renter_id = r.renter_id
GROUP BY r.first_name, r.last_name
HAVING COUNT(*) > 2;