mysql - 关于sql语句中的with从句和group by分组
怪我咯
怪我咯 2017-04-17 16:36:17
0
1
554

初涉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语句实现呢?

怪我咯
怪我咯

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

reply all(1)
伊谢尔伦

The question is to choose "passengers' favorite car model". The following Postgresql code is not tested:

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 is the model-passenger relationship table, which has been distinct processed. brand_cusid是车型-乘客的关系表,已做distinct处理。

  • 然后按carbrand分组并按行数从大到小排序,并显示前10个车型。

  • 注意这些车型有可能是并列第一的。这时可增加limit

Then group by carbrand and sort by row number from large to small, and display the top 10 models. 🎜🎜 🎜🎜Note that these models may be tied for first place. At this time, the limit quantity can be increased. 🎜🎜 🎜
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template