mysql - 关于sql语句中的with从句和group by分组
本文介绍了mysql - 关于sql语句中的with从句和group by分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
初涉SQL,对于其中with
和group by
从句搭配sum
,max
方法的使用逻辑有一些疑问
例如,数据库中有以下几个table
Customer (cusid, cusname, cusphone, cuscity);
Driver (did, dname, dphone, dcity);
CarOwnership (did, carid);
Car (carid, carbrand, carsize);
Trips (cusid, carid, did, getontime, getofftime, price, distance);
要output出 carbrand
。这个carbrand
是最多distinct customer
使用过的,即求每一种carbrand
的distinct cusid
数量sum
,再求max
这个数量的carbrand
,应该如何使用sql语句实现呢?
解决方案
题主是想选出乘客最喜爱的车型。以下Postgresql代码未测试:
select carbrand, count(*) as customers
from (
select distinct carbrand, cusid
from Trips inner join Car using (carid)) as brand_cusid
group by carbrand
order by customers desc
limit 10
brand_cusid
是车型-乘客的关系表,已做distinct
处理。然后按
carbrand
分组并按行数从大到小排序,并显示前10个车型。注意这些车型有可能是并列第一的。这时可增加
limit
数量。
这篇关于mysql - 关于sql语句中的with从句和group by分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文