mysql - 關(guān)于sql語句中的with從句和group by分組
問題描述
初涉SQL,對(duì)于其中with和group by從句搭配sum,max方法的使用邏輯有一些疑問
例如,數(shù)據(jù)庫中有以下幾個(gè)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。這個(gè)carbrand是最多distinct customer使用過的,即求每一種carbrand的distinct cusid數(shù)量sum,再求max這個(gè)數(shù)量的carbrand,應(yīng)該如何使用sql語句實(shí)現(xiàn)呢?
問題解答
回答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是車型-乘客的關(guān)系表,已做distinct處理。
然后按carbrand分組并按行數(shù)從大到小排序,并顯示前10個(gè)車型。
注意這些車型有可能是并列第一的。這時(shí)可增加limit數(shù)量。
相關(guān)文章:
1. javascript - 關(guān)于apply()與call()的問題2. 安全性測試 - nodejs中如何防m(xù)ySQL注入3. java - spring boot 如何打包成asp.net core 那種獨(dú)立應(yīng)用?4. java - 在用戶不登錄的情況下,用戶如何添加保存到購物車?5. javascript - nginx反向代理靜態(tài)資源403錯(cuò)誤?6. docker網(wǎng)絡(luò)端口映射,沒有方便點(diǎn)的操作方法么?7. docker - 各位電腦上有多少個(gè)容器啊?容器一多,自己都搞混了,咋辦呢?8. MySQL 查詢疑問?9. 推薦好用mysql管理工具?for mac和pc10. javascript - 如何將函數(shù)計(jì)算出的內(nèi)容傳遞為變量
