DROP SCHEMA tmp CASCADE;
CREATE SCHEMA tmp ;
SET search_path=tmp;
CREATE TABLE lutser
(id INTEGER NOT NULL
, category INTEGER NOT NULL
);
INSERT INTO lutser(category, id) VALUES
(1,1100) ,(1,1200) ,(1,1300) ,(1,1500)
,(2,2000) ,(2,2100) ,(2,2300) ,(2,2500)
,(1,3500) -- added these
,(2,3500)
;
這些查詢構建一個「位掩碼」 1類== 1,2類== 2,並添加它們。因此,當兩個集合中都存在id時,掩碼爲3,僅在第一個集合中爲1,而僅在第二集合中爲2。外部連接+聚合在這裏做的伎倆。
--
-- CTE version
--
WITH flags AS (
WITH one AS (SELECT category AS flag , id FROM lutser WHERE category = 1)
, two AS (SELECT category AS flag , id FROM lutser WHERE category = 2)
SELECT COALESCE(one.flag, 0) + COALESCE(two.flag, 0) AS flag
FROM one
FULL OUTER JOIN two ON two.id = one.id
)
SELECT flag, COUNT(*)
FROM flags
GROUP BY flag;
--
-- Non-CTE version
--
SELECT COALESCE(one.flag, 0) + COALESCE(two.flag, 0) AS flags
, COUNT(*)
FROM (
SELECT category AS flag , id
FROM lutser WHERE category = 1
) one
FULL OUTER JOIN (
SELECT category AS flag , id
FROM lutser WHERE category = 2
) two ON two.id = one.id
GROUP BY flags;
結果(這兩個查詢;-):
flags | count
-------+-------
1 | 4
2 | 4
3 | 1
專家給解答快速:-) – vels4j