Sql 从两个具有多个计数的表中进行选择
我有两个表正试图加入select查询 表1:存储,主键(id,存储编号) 表2:部门,状态(A-已申请,p-待决) 应选择门店id、门店编号、截止日期、经理id、已应用计数、待处理计数。结果是这样的Sql 从两个具有多个计数的表中进行选择,sql,join,count,Sql,Join,Count,我有两个表正试图加入select查询 表1:存储,主键(id,存储编号) 表2:部门,状态(A-已申请,p-待决) 应选择门店id、门店编号、截止日期、经理id、已应用计数、待处理计数。结果是这样的 store_id store_num due_date manager_id applied_count pending_count 1 100 06-30-2024 user1 4
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
你的查询完成了一半。您需要进行聚合以获取不同列中的值。这是一个条件聚合,如下所示:
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,
正在计算状态为'A'
的行数。它通过为这些行指定一个1
值,然后对该值求和来实现
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,