[英]SQL Query to Count Distinct with Group By with a Join
在序數過程中,有許多位置具有成員處於不同步驟。 成員可以處於多個進程中,在一個或多個位置具有不同的進度。
位置和成員之間的連接表可能看起來像這樣稱為步驟。
| id | member_id | step_no | location_id | process_id |
-------------------------------------------------------
| 1 | 1 | 2 | 10 | 57
| 2 | 1 | 5 | 10 | 58
| 3 | 2 | 5 | 11 | 37
| 4 | 2 | 1 | 10 | 57
我無法確定如何根據位置獲得成員在流程中最遠步驟的唯一成員數。
location_id | 1 | 2 | 3 | 4 | 5 |
---------------------------------
10 | 1 | 0 | 0 | 0 | 1 |
11 | 0 | 0 | 0 | 0 | 1 |
到目前為止,我有這個查詢:
SELECT count(DISTINCT m.id), l.id, l.name
FROM members m
INNER JOIN steps s ON m.id = s.member_id
INNER JOIN locations l ON s.location_id = l.id
WHERE step_no = 5
GROUP BY l.id
ORDER BY l.name
但是這當然只返回step_no = 5,如果我寫了五個這樣的查詢,那么成員可以在不同的步驟中被計算兩次。
select
location_id
,sum(case when max_step = 1 then 1 else 0 end) as step_one_cnt
,sum(case when max_step = 2 then 1 else 0 end) as step_two_cnt
,sum(case when max_step = 3 then 1 else 0 end) as step_three_cnt
,sum(case when max_step = 4 then 1 else 0 end) as step_four_cnt
,sum(case when max_step = 5 then 1 else 0 end) as step_five_cnt
FROM
(select
s.location_id,
s.member_id,
max(s.step_no) as max_step
FROM steps S
group by 1,2
) as base
group by 1
打破它,基本查詢會給你以下結果:
member_id | location_id | max_step_no
-------------------------------------------------------
| 1 | 10 | 5
| 2 | 10 | 1
| 2 | 11 | 5
此子查詢(基礎)上的聚合查詢基本上將結果轉換為您希望看到的形式。 此方法的唯一限制是步驟數在高級中靜態定義。
1-首先在臨時表中選擇以下內容:
select location_id , step_no , count(member_id) as count
into stepsPrime
from (select member_id, location_id, max(step_no) as step_no
from steps
group by member_id, location_id ) definedTab
group by location_id, step_no
order by location_id;
2-使用以下查詢來旋轉上述結果:
select distinct stp.location_id,
stp1.count as step1,
stp2.count as step2,
stp3.count as step3,
stp4.count as step4,
stp5.count as step5
from stepsPrime stp
left join stepsPrime stp1 on stp.location_id = stp1.location_id and stp1.step_no = 1
left join stepsPrime stp2 on stp.location_id = stp2.location_id and stp2.step_no = 2
left join stepsPrime stp3 on stp.location_id = stp3.location_id and stp3.step_no = 3
left join stepsPrime stp4 on stp.location_id = stp4.location_id and stp4.step_no = 4
left join stepsPrime stp5 on stp.location_id = stp5.location_id and stp5.step_no = 5;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.