我有2个表,我正在尝试加入选择查询。
表1:Store,primary_key(id,store_num)
store_id store_num due_date manager_id
1 100 06-30-2024 user1
2 108 06-30-2018 user2
3 109 13-31-2014 user3
表2:部门,状态(已应用A,待定)
store_id store_num dept_num status
1 100 201 A
1 100 202 A
1 100 203 P
1 100 204 A
1 100 205 P
1 100 206 A
期望选择store_id,store_num,due_date,manager_id,应用计数,待处理计数。结果是这样的。
store_id store_num due_date manager_id applied_count pending_count
1 100 06-30-2024 user1 4 2
我尝试了它并且得到了我能够加入并在多行中获取的地方,但是对我来说没有用。有人可以帮助我如何获得计数
select
store.store_id,
store.store_num,
store.due_date,
store.manager_id,
dept.status
from store as store
inner join department as dept on store.store_id = dept.store_id
and store.store_num = dept.store_num
答案 0 :(得分:2)
您的查询已完成一半。您需要进行聚合以获取不同列中的值。这是一个条件聚合,如下所示:
select s.store_id, s.store_num, s.due_date, s.manager_id,
sum(case when d.status = 'A' then 1 else 0 end) as Active_Count,
sum(case when d.status = 'P' then 1 else 0 end) as Pending_Count
from store s inner join
department as dept
on s.store_id = d.store_id and s.store_num = d.store_num
group by store.store_id, store.store_num, store.due_date, store.manager_id;
表达式:
sum(case when d.status = 'A' then 1 else 0 end) as Active_Count,
计算status = 'A'
所在的行。它通过为这些行分配值1
,然后将该值汇总来实现。