嵌套计数

时间:2019-01-16 16:36:29

标签: sql

我想知道如何将计数查询作为具有count(*)的变量放置

通常,我希望这段代码返回order_ID,其中所有子订单(在同一order_ID中,它们由另一个键区分)

select order_id, count(*)
from order     
where status = 10  
group by order_id

having count(*) = X <-- here I want to put a total number of suborders which I can get by following query:


select order_id, count(order_id) from order 
group by order_id 

如何将它们放在一起?

我正在使用的示例性数据如下:(我在这里有些混乱,sub_ids是另一个表中的主键,而order_id是外来的,但是我处理了联接,在这种情况下这不是问题)

order_id = 1  sub_id = 1  status = 10
order_id = 1  sub_id = 2  status = 5
order_id = 1  sub_id = 3  status = 5

order_id = 2  sub_id = 1  status = 10
order_id = 2  sub_id = 2  status = 10
order_id = 2  sub_id = 3  status = 10
order_id = 2  sub_id = 4  status = 10
order_id = 2  sub_id = 5  status = 10

order_id = 3  sub_id = 6  status = 0
order_id = 3  sub_id = 7  status = 10

在这种情况下,我希望此查询返回order_id = 2

3 个答案:

答案 0 :(得分:1)

SELECT
    *
FROM
(
    SELECT
        order_id,
        COUNT(*)                                  cnt_all,
        COUNT(CASE WHEN status = 10 THEN 1 END)   cnt_s10
    FROM
        yourTable
    GROUP BY
        order_id
)
    AS order_summary
WHERE
    cnt_all = cnt_s10

答案 1 :(得分:0)

这有点复杂,但是。 。

select order_id,
       sum(case when status = 10 then 1 else 0 end) as cnt_status_10
from order o     
group by order_id
having count(*) = X;

与您的查询不同,这将返回cnt_status_100的订单。如果要排除这些:

having count(*) = X and cnt_status_10 > 0;

如果您的数据库在having子句中不允许使用别名,请使用完整表达式。

答案 2 :(得分:0)

由于这是子订单表,因此order_id不能为空。所以count(order_id)就是count(*)

这意味着您正在查找仅包含状态10子订单的订单(状态10的数量=总数量)。就是这样:

select order_id, count(*)
from suborder     
group by order_id
having count(case when status = 10 then 1 end) = count(*);

(为了避免与非唯一的order_id混淆,我在查询中对表进行了重命名。)