[英]Correlated subquery in order by clause in DB2
I had a query similar to the following and was wondering that DB2 complained about the correlation use in the ORDER BY clause. 我有一个类似于以下的查询,并且想知道DB2抱怨ORDER BY子句中的相关性使用。 It errored with something like
出现类似错误
[42703][-206] "A.ID" is not valid in the context where it is used.. SQLCODE=-206, SQLSTATE=42703
[42703] [-206]“ A.ID”在使用上下文中无效。SQLCODE = -206,SQLSTATE = 42703
I was able to rewrite the query to avoid the correlation usage but I couldn't find a reference in the documenation about this. 我能够重写查询以避免使用相关性,但是我在文档中找不到与此相关的参考。 Is this a bug or am I just not able to find details on the expected behavior?
这是错误还是我只是无法找到预期行为的详细信息?
SELECT a.id
FROM A a
ORDER BY (
SELECT COUNT(*)
FROM B b
WHERE b.id = a.id
)
You can't use correlated query in order by clause. 您不能在order by子句中使用相关查询。 However there is many ways to get same result, for example
但是,有很多方法可以获得相同的结果,例如
select count(*) as count_num ,a.ID
from
a join b on a.ID=b.ID
GROUP BY a.ID
order by 1 DESC
solution 1: 解决方案1:
SELECT a.id, (select count(*) from B where B.id=a.id) nbOFB
FROM A
order by 2
solution 2: 解决方案2:
select * from (
SELECT a.id, (select count(*) from B where B.id=a.id) nbOFB
FROM A
) tmp
order by nbOFB
Solution 3: 解决方案3:
SELECT a.id, c.nb
FROM A
inner join lateral
(
select count(*) nb from B where B.id=a.id
) c on 1=1
order by c.nb
Solution 4 : 解决方案4:
SELECT a.id, ifnull(c.nb, 0) nb
FROM A
left outer join
(
select b.id, count(*) nb from B group by b.id
) c on a.id=c.id
order by ifnull(c.nb, 0)
Solution 5: 解决方案5:
with c as (
select b.id, count(*) nb from B group by b.id
)
SELECT a.id, ifnull(c.nb, 0) nb
FROM A left outer join c on a.id=c.id
order by ifnull(c.nb, 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.