mysql - 關(guān)于sql語句中的with從句和group by分組
問題描述
初涉SQL,對于其中with和group by從句搭配sum,max方法的使用邏輯有一些疑問
例如,數(shù)據(jù)庫中有以下幾個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數(shù)量sum,再求max這個數(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個車型。
注意這些車型有可能是并列第一的。這時可增加limit數(shù)量。
相關(guān)文章:
1. docker 17.03 怎么配置 registry mirror ?2. 前端 - @media query 使用出現(xiàn)的問題?3. docker 下面創(chuàng)建的IMAGE 他們的 ID 一樣?這個是怎么回事????4. node.js - mongodb查找子對象的名稱為某個值的對象的方法5. 運(yùn)行python程序時出現(xiàn)“應(yīng)用程序發(fā)生異常”的內(nèi)存錯誤?6. html5 - datatables 加載不出來數(shù)據(jù)。7. 測試自動化html元素選擇器元素ID或DataAttribute [關(guān)閉]8. javascript - QQ第三方登錄的問題9. 利用IPMI遠(yuǎn)程安裝centos報錯!10. spring-mvc - spring-session-redis HttpSessionListener失效

網(wǎng)公網(wǎng)安備