【问题标题】:select from 2 tables with multiple counts从具有多个计数的 2 个表中选择
【发布时间】:2013-06-23 01:13:38
【问题描述】:

我有 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:部门,其中状态(A-已申请,p-待定)

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

【问题讨论】:

    标签: sql join count


    【解决方案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,
    

    正在计算status = 'A' 所在的行。它通过为这些行分配一个值 1 然后将该值相加来实现。

    【讨论】:

      猜你喜欢
      • 2014-10-17
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      • 2019-11-09
      • 2015-02-19
      • 1970-01-01
      • 2016-12-22
      • 1970-01-01
      相关资源
      最近更新 更多