我有兩張桌子:
顧客:
| ID | 名稱 | 地址 ID |
|---|---|---|
| 1 | 約翰 | 4 |
| 2 | 凱特 | 5 |
| 3 | 鮑勃 | 2 |
| 4 | 邁克爾 | 2 |
| 5 | 阿德里亞娜 | 3 |
| 6 | 安 | 1 |
地址:
| ID | detail_str_name | 城市 | 區 | 街道名稱 |
|---|---|---|---|---|
| 1 | 法國,巴黎,str.2,N5 | 巴黎 | 巴黎 | 字串 2 |
| 2 | 法國,巴黎,str.2,N3 | 巴黎 | 巴黎 | 字串 2 |
| 3 | 法國,里爾,str.3,N4 | 里爾 | 里爾 | str.3 |
| 4 | 法國,巴黎,str.4,N3 | 巴黎 | 巴黎 | 字串 4 |
| 5 | 法國, 巴黎, Batignolles,N4 | 巴黎 | 巴蒂尼奧勒 | 巴蒂尼奧勒 |
我想要這樣的表:
| 名稱 | detail_str_name | 城市 | 區 | 街道名稱 | 總和(cu.num_cust) |
|---|---|---|---|---|---|
| 約翰 | 法國,巴黎,str.4,N3 | 巴黎 | 巴黎 | 字串 4 | 1 |
| 凱特 | 法國, 巴黎, Batignolles,N4 | 巴黎 | 巴蒂尼奧勒 | 巴蒂尼奧勒 | 1 |
| 鮑勃 | 法國,巴黎,str.2,N3 | 巴黎 | 巴黎 | 字串 2 | 3 |
| 邁克爾 | 法國,巴黎,str.2,N3 | 巴黎 | 巴黎 | 字串 2 | 3 |
| 阿德里亞娜 | 法國,里爾,str.3,N4 | 里爾 | 里爾 | str.3 | 1 |
| 安 | 法國,巴黎,str.2,N5 | 巴黎 | 巴黎 | 字串 2 | 3 |
我想按城市、地區和街道名稱計算客戶群,而不是 detail_str_name。
我嘗試:
select cu..name,ad.detail_str_name, ad.city,ad.district, ad.street_name,sum(cu.num_cust)
from
(select address_id, name,count (id) as num_cust
from customer
group by address_id,name) cu
left join address ad on cu.address_id = ad.id
group by cu..name,ad.detail_str_name, ad.city,ad.district, ad.street_name
但是,此代碼按 detail_str_name 分組,這不適合我。
我能改變什么?
uj5u.com熱心網友回復:
我無法檢查這個,所以它可能不完全正確,但我認為下面的查詢應該得到你需要的資料。
這SQLTutorial文章通過子句磁區可能是有用的。
SELECT cu.name,
ad.detail_str_name,
ad.city,
ad.district,
ad.street_name,
COUNT(cu.name) OVER(PARTITION BY ad.city, ad.district, ad.street_name) AS 'num_cust'
FROM customer cu
JOIN address ad ON ad.id = cu.address_id
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/385707.html
