将相同的表连接两次以用于不同列中的计数

时间:2015-04-29 16:45:28

标签: sql postgresql

我有2张桌子

A
+----+-------+
| Id | User  |
+----+-------+
|  1 | user1 |
|  2 | user2 |
|  3 | user3 |
+----+-------+

B
+----+--------+------+
| Id | UserId | Type |
+----+--------+------+
|  1 |      1 | A    |
|  2 |      1 | B    |
|  3 |      1 | C    |
|  4 |      2 | A    |
|  5 |      2 | B    |
|  6 |      2 | C    |
|  7 |      3 | A    |
|  8 |      3 | C    |
+----+--------+------+

UserId is FK from table A.Id

我尝试使用单个SQL查询来计算每种类型和类型排列,如下所示。 (例如,计数A ^ B表示具有类型A和B的用户数)

+---------+---------+---------+-----------+-----------+-----------+-------------+
| Count A | Count B | Count C | Count A^B | Count A^C | Count B^C | Count A^B^C |
+---------+---------+---------+-----------+-----------+-----------+-------------+
|       3 |       2 |       3 |         2 |         3 |         2 |           2 |
+---------+---------+---------+-----------+-----------+-----------+-------------+

或针对每个排列计数单独查询。

我在下面尝试查询以分别计算A类和B类,但它没有工作。

SELECT count(b1.type) AS count_a, count(b2.type) AS count_b FROM A 
JOIN B on A.id = B.user_id
WHERE b1.type = 'A' or b2.type = 'B' 
GROUP BY A.id;

+---------+---------+
| Count A | Count B |
+---------+---------+
|       3 |       2 |
+---------+---------+

1 个答案:

答案 0 :(得分:0)

也许我正在解释这个错误,但我认为你可以在你的select语句中做一个非常简单的case语句,而不是计算一个SUM:

SELECT SUM(CASE b.Types WHEN 'A' THEN 1 ELSE 0) as COUNT_A,
       SUM(CASE b.Types WHEN 'B' THEN 1 ELSE 0) as COUNT_B
FROM  A 
JOIN B
ON A.id = B.user_id
WHERE b1.type = 'A' or b2.type = 'B'