如何找出同一张表中特定状态的多个计数

Posted

技术标签:

【中文标题】如何找出同一张表中特定状态的多个计数【英文标题】:how to find out the multiple counts of specific status in the same table 【发布时间】:2021-01-18 03:20:17 【问题描述】:

我有 Orders 和 OrderSubscription 表。表之间的关系是一对多的。我想找出其中一个 OrderSubscription 状态必须为“Active”和“Cancelled”并且应该有多个“Pending”状态的订单。

所以最终结果应该是 order id =2 记录。

编写了以下查询及其工作正常。或者还有其他更好的方法来过滤记录吗?

select o.id,
       o.order_number,
       o.order_status
  from Orders o
 
 where o.order_status = 'Active' AND
   1=(select count(*) from OrderSubscription where order_id = o.id and subs_status='Active')
    AND
   1=( select count(*) from OrderSubscription where  order_id = o.id and subs_status='Cancelled')
   AND
   1 < (select count(*) from OrderSubscription where  order_id = o.id and subs_status='Pending')
 group by o.id,
          o.order_number,
          o.order_status
 order by o.id;
 
 
 
 

Create Table Orders(id number(5),order_number number(12),order_status varchar2(20));

insert into Orders Values (1,12345,'Active');
insert into Orders Values (2,5757575,'Active');
insert into Orders Values (3,979797979,'Active');
insert into Orders Values (4,3131313133,'Active');

Create Table OrderSubscription(id number(5),order_id number(5),subs_name varchar2(20),subs_status varchar2(20));

insert into OrderSubscription Values(1,1,'360 fhf','Pending');
insert into OrderSubscription Values (2,1,'720 cef','Active');
insert into OrderSubscription Values (3,1,'540 abc','Cancelled');


insert into OrderSubscription Values (1,2,'360 fhf','Active');
insert into OrderSubscription Values (2,2,'720 cef','Pending');
insert into OrderSubscription Values (3,2,'540 abc','Pending');
insert into OrderSubscription Values (4,2,'adada abc','Cancelled');


insert into OrderSubscription Values (1,3,'720 cef','Pending');
insert into OrderSubscription Values (2,3,'60 ert','Active');
insert into OrderSubscription Values (3,3,'60 ert','Cancelled');

insert into OrderSubscription Values (1,4,'360 fhf','Pending');
insert into OrderSubscription Values (2,4,'560 fhf','Pending');
insert into OrderSubscription Values (3,4,'560 fhf','Active');

【问题讨论】:

这好像是Oracle,为什么还要加SQL Server标签? 我在 oracle 中写过,但实际上这也应该在 sql server 中工作。 【参考方案1】:

您似乎想使用条件聚合方法。一种正确的方法是按订单号聚合,然后断言各种状态计数。

SELECT o.order_number
FROM Orders o
INNER JOIN OrderSubscription os
    ON os.order_id = o.id
WHERE
    o.order_status = 'Active'
GROUP BY
    o.order_number
HAVING
    COUNT(CASE WHEN os.subs_status = 'Active'    THEN 1 END) > 0 AND
    COUNT(CASE WHEN os.subs_status = 'Cancelled' THEN 1 END) > 0 AND
    COUNT(CASE WHEN os.subs_status = 'Pending'   THEN 1 END) > 1;

【讨论】:

以上是关于如何找出同一张表中特定状态的多个计数的主要内容,如果未能解决你的问题,请参考以下文章

同一张表上的多个连接:转换状态

使用 JOIN'ed 映射表比同一张表中的多个字段更好?

如何在 sql server 2008 的同一张表中使用计数和分组方式和自连接?

Google 表格根据多个条件返回值

如何将特定列单元格映射到同一张表中的其他特定列单元格?

oracle查询填补同一张表中缺失的数据