子查询 SQL ,根据子查询结果得到ID的个数
Subquery SQL , get the count of ID's based on the subquery results
我写过这样的子查询-
Select ID, count(*) as cn from xyz group by 1
结果输出为-
ID
cn
A
3
B
45
现在我正在做这个查询-
SELECT CASE
WHEN temp.cn > 10 THEN Count(DISTINCT id)
END AS cn_10,
CASE
WHEN temp.cn <= 10 THEN Count(DISTINCT id)
END AS cn_9
FROM (SELECT id,
Count(*) AS cn
FROM xyz
GROUP BY 1) AS temp;
希望得到像
这样的输出
cn_10
cn_9
300
400
但是我一直收到这个错误,
SQL compilation error: [temp.cn] is not a valid group by expression
您可以在聚合中使用 case 表达式,如下所示,当然未经测试,但这对您有用吗?
select
Count(case when cn > 10 then 1 end) cn_10,
Count(case when cn <= 10 then 1 end) cn_9
from (
select id, Count(*) cn
from xyz
group by Id
)t;
我写过这样的子查询-
Select ID, count(*) as cn from xyz group by 1
结果输出为-
ID | cn |
---|---|
A | 3 |
B | 45 |
现在我正在做这个查询-
SELECT CASE
WHEN temp.cn > 10 THEN Count(DISTINCT id)
END AS cn_10,
CASE
WHEN temp.cn <= 10 THEN Count(DISTINCT id)
END AS cn_9
FROM (SELECT id,
Count(*) AS cn
FROM xyz
GROUP BY 1) AS temp;
希望得到像
这样的输出cn_10 | cn_9 |
---|---|
300 | 400 |
但是我一直收到这个错误,
SQL compilation error: [temp.cn] is not a valid group by expression
您可以在聚合中使用 case 表达式,如下所示,当然未经测试,但这对您有用吗?
select
Count(case when cn > 10 then 1 end) cn_10,
Count(case when cn <= 10 then 1 end) cn_9
from (
select id, Count(*) cn
from xyz
group by Id
)t;