mysql - 关于sql语句中的with从句和group by分组
怪我咯
怪我咯 2017-04-17 16:36:17
[MySQL讨论组]

初涉SQL,对于其中withgroup by从句搭配summax方法的使用逻辑有一些疑问

例如,数据库中有以下几个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使用过的,即求每一种carbranddistinct cusid数量sum,再求max这个数量的carbrand,应该如何使用sql语句实现呢?

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(1)
伊谢尔伦

题主是想选出“乘客最喜爱的车型”。以下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数量。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号