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语句实现呢?
问题解答
回答1:题主是想选出“乘客最喜爱的车型”。以下Postgresql代码未测试:
select carbrand, count(*) as customersfrom ( select distinct carbrand, cusid from Trips inner join Car using (carid)) as brand_cusidgroup by carbrandorder by customers desclimit 10
brand_cusid是车型-乘客的关系表,已做distinct处理。
然后按carbrand分组并按行数从大到小排序,并显示前10个车型。
注意这些车型有可能是并列第一的。这时可增加limit数量。
相关文章:
1. ddos - apache日志很多其它网址,什么情况?2. boot2docker无法启动3. css3 - css的伪类作用?4. 安卓某些机型播放HTML5 video会卡死5. 利用百度地图API定位及附件商家信息服务6. webpack - vue-cli写的项目(本地跑没有问题),准备放到Nginx服务器上,有什么配置需要改的?还有怎么部署?7. 微信公众号发送模板消息返回错误410008. css - weui 用伪元素生成border,源码有点不理解9. javascript - 关于audio标签暂停的问题10. javascript - 调微信分享朋友接口,出现下面问题,求解答,
