编写查询以显示访问次数最多的客户名称
select customer_id,count(*) from booking group by customer_id ;
使用此查询我获得了每位客户的访问次数,如下所示
CUSTOMER_ID,COUNT(*)
C001,6
C002,1
C003,1
C004,1
C005,4
但我想只显示c005,因为他已经访问了第二个最长时间
答案 0 :(得分:1)
SELECT customer_id, COUNT(*)
FROM booking
GROUP BY customer_id
HAVING COUNT(*) <> (SELECT MAX(t.custCount)
FROM (SELECT COUNT(*) AS custCount
FROM booking
GROUP BY customer_id) t )
ORDER BY COUNT(*) DESC
LIMIT 1
作为旁注,如果有第二名的关系,这将不会起作用。在这种情况下,您使用上述查询作为WHERE
子句中的条件,例如
SELECT customer_id
FROM booking
GROUP BY customer_id
HAVING COUNT(*) = (query given above)
答案 1 :(得分:0)
您可以使用外部查询并过滤相同的内容,例如
select customer_id from (
select customer_id,
count(*) as datacount
from booking
group by customer_id ) xxx
order by datacount desc
limit 1;