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. javascript - 在 model里定義的 引用表模型時,model為undefined。2. css3 - 這個右下角折角用css怎么畫出來?3. javascript - canvas 裁剪空白區域4. atom開始輸入!然后按tab只有空格出現沒有html格式出現5. css3 - 沒明白盒子的height隨width的變化這段css是怎樣實現的?6. java - 我設置了cookie的max age,但是cookie依然在關閉游覽器后消失了7. apache - 想把之前寫的單機版 windows 軟件改成網絡版,讓每個用戶可以注冊并登錄。類似 qq 的登陸,怎么架設服務器呢?8. javascript - 一個關于客戶端和前端通信的疑惑?9. python3.x - c++調用python310. java - 根據月份查詢多個表里的內容怎么實現好?
