从表中选择与其他表相比具有不同count()的项目

时间:2018-10-12 17:22:34

标签: sql postgresql

我有两个表,例如:

Table A:
  userid
-----------
 A
 B
 C
 D
 D

Table B:
  userid
-----------
 A
 B
 C
 D
 D
 D
 E

我需要从表B中获得表B上的count()与表A上的count()不同的项目。从上面的示例中,我需要打印它:

Table Result:
-----------
D
E

有可能吗?

3 个答案:

答案 0 :(得分:1)

SELECT B.userid
FROM (SELECT userid, count(*) AS countB FROM TableB GROUP BY userid) B
  LEFT JOIN (SELECT userid, count(*) AS countA FROM TableA GROUP BY userid) A USING(userid)
WHERE A.countA != B.countB OR A.countA IS NULL;

已编辑以添加沙箱进行测试:https://rextester.com/CTKD25341

答案 1 :(得分:1)

好吧,首先,您需要获取表的计数。像这样:

SELECT userid, COUNT(*) as count
FROM a
GROUP BY userid;

从'b'获取计数将非常相似。

如果您将这两个查询结果都作为表,那么要获得结果,您需要执行以下操作:

SELECT DISTINCT aa.userid
FROM aa, bb
WHERE
  aa.userid = bb.userid AND 
  aa.count != bb.count;

幸运的是,您可以将所有类似的内容组合在一起

WITH aa AS (
  SELECT userid, COUNT(*) as count
  FROM a
  GROUP BY userid),
bb AS (
  SELECT userid, COUNT(*) as count
  FROM b
  GROUP BY userid)
SELECT DISTINCT aa.userid
FROM aa, bb
WHERE
  aa.userid = bb.userid AND 
  aa.count != bb.count;

但是,在输出中缺少“ E”。因此,我们需要执行不同的联接,并选择其他内容:

SELECT DISTINCT COALESCE(aa.userid, bb.userid)
FROM aa
  FULL OUTER JOIN bb
  ON aa.userid = bb.userid
WHERE
  (aa.count != bb.count
   OR aa.count IS NULL
   OR bb.count IS NULL);

FULL OUTER JOIN是为了确保在一个表中有行但在另一个表中没有行的情况下得到结果。这会添加带有NULL值的行,我们需要考虑这些值。 COALESCE获取第一个非NULL值(因此,如果表b具有'X',而表a没有,则它将获取'X')。

最后,计数中也可能有NULL,所以我们来处理。

所有看起来像这样:

WITH aa AS (
  SELECT userid, COUNT(*) as count
  FROM a
  GROUP BY userid),
bb AS (
  SELECT userid, COUNT(*) as count
  FROM b
  GROUP BY userid)
SELECT DISTINCT COALESCE(aa.userid, bb.userid)
FROM aa
  FULL OUTER JOIN bb
  ON aa.userid = bb.userid
WHERE
  (aa.count != bb.count
   OR aa.count IS NULL
   OR bb.count IS NULL);

SQLFiddle here

编辑后添加:肯定有更紧凑的方法可以做到这一点(其他答案也证明了这一点)。这种方式的好处是可以通过简单的查询来建立,这就是为什么我喜欢它。

答案 2 :(得分:0)

我也自己做了一个

select distinct userid from table_b where 
(select count(userid) from table_b where userid = a.userid) != 
(select count(userid) from table_a where userid = a.userid);