2

我有一个表,其中包含两列中的常见条目。

例如:

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
4

1 回答 1

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
于 2012-06-16T12:35:23.557 回答