我有一个类似以下的查询,但没有工作:
SELECT COUNT(*) as count, a.COUNT(*) AS total
FROM A
WHERE key IN (SELECT key
FROM B
WHERE condition
) a
GROUP BY key;
我也希望得到总数结果
(SELECT key
FROM B
WHERE condition
)
我如何给它贴上标签,并在外部选择中使用它?还是其他任何方法?感谢?
答案 0 :(得分:0)
您正在寻找的是Left Join
SELECT a.key, sum(b.bCount) as count, a.COUNT(*) AS total
FROM A
LEFT JOIN (
SELECT key, COUNT(1) as bCount
FROM B
WHERE condition
) b
on A.key = b.key
GROUP BY key;
答案 1 :(得分:0)
如果我正确理解你的目标:
with
a1 as (select key, count(*) as cnt from a group by key),
b1 as (select key, count(*) as cnt from b where condition group by key)
select
a1.key, a1.cnt, b1.cnt
from
a1 join b1 on (a1.key = b1.key)
答案 2 :(得分:0)
在PG identifiers are case-insensitive中。因此,在您的查询表中A
和子查询a
与服务器是相同的,这是不可能的。实际上,即使您执行了a
,该表也可能被称为CREATE TABLE A (...)
。只有在创建时双引号表名称(例如"A"
),才会保留该案例,但是您还应该在所有查询中双引号表名称。为子查询提供不同的标签或双引表名将使错误消失。
在您的子查询中,如果您希望主查询中提供该信息,则需要进行计数。而不是相关的子查询 - key IN ...
- 您应该进行两个子查询(因为它们分组可能不同的不同关系)并在主查询中JOIN
:
SELECT key, sub1.count, sub2.total
FROM (
SELECT key, count(*) AS count FROM a
GROUP BY key ) sub1
JOIN (
SELECT key, count(*) AS total FROM b
WHERE condition
GROUP BY key ) sub2 USING (key);