2015-04-29 103 views
9

我有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查詢。 (例如計數甲^ 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 | 
+---------+---------+ 
+0

我不確定哪裏有兩個表或者^ ^代表什麼 –

+0

@ExplosionPills這些只是列別名。 –

+0

我更新了問題。希望它能解釋得更好。 基本上,計數A^B意味着具有A型和B型的用戶數 –

回答

7

你可以寫:

select count(case when "Types" @> array['A'] then 1 end) as "COUNT A", 
     count(case when "Types" @> array['B'] then 1 end) as "COUNT B", 
     count(case when "Types" @> array['C'] then 1 end) as "COUNT C", 
     count(case when "Types" @> array['A','B'] then 1 end) as "COUNT A^B", 
     count(case when "Types" @> array['A','C'] then 1 end) as "COUNT A^C", 
     count(case when "Types" @> array['B','C'] then 1 end) as "COUNT B^C", 
     count(case when "Types" @> array['A','B','C'] then 1 end) as "COUNT A^B^C" 
    from (select array_agg("Type"::text) as "Types" 
      from "B" 
      group by "UserId" 
     ) t 
; 

的想法是,首先,我們使用的是生產,爲每個用戶,包含他/她的類型的數組的子查詢;然後外部查詢只計算包含每組類型的數組。

你可以看到它在行動http://sqlfiddle.com/#!15/cbb45/1。 (我還包含有子查詢的修改版本,以幫助您瞭解它是如何工作的。)

一些相關PostreSQL文檔:

+0

這是非常好的。我們希望COUNT()在這裏還是SUM()? –

+0

此查詢完全符合我的需求。非常感謝! –

+0

@AmilOsmanli:不客氣! – ruakh

0

也許我正在解釋這個錯誤,但我認爲你可以在你的select語句中做一個非常簡單的case語句,而不是count做一個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'