0

我有 2 个表正在尝试加入选择查询。

表 1:存储,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:部门,where status(A-applied,p-Pending)

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、Applied count、pending count。结果是这样的。

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
4

1 回答 1

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然后对该值求和来实现这一点。

于 2013-06-26T03:15:46.673 回答