我有一个包含两列常用条目的表。
例如:
Column1 Column2
Entry1 || NULL
Entry2 || Entry1
Entry3 || Entry1
Entry4 || Entry4
Entry5 || NULL
我想查找第1列的条目出现在第2列的次数。
所以结果会是这样的:
Column1 Count
Entry1 || 2
Entry2 || 0
Entry3 || 0
Entry4 || 1
Entry5 || 0
答案 0 :(得分:2)
WITH counts AS (
SELECT column2, COUNT(*) AS the_count
FROM x
GROUP BY column2
)
SELECT x.column1, COALESCE(c.the_count, 0)
FROM x LEFT OUTER JOIN counts c ON (x.column1 = c.column2)
ORDER BY 1