Postgresql
根據列獲得不同的結果並滿足條件
我有以下選擇,它從包含列的表中選擇:
id、project_id、keyword_id、位置、數據範例:
i, p_id, k_id, p 1, 1, 1, 4 2, 1, 1, 5 3, 1, 1, 6 5, 1, 2, 7 6, 1, 2, 8 7, 1, 3, 5 8, 1, 3, 7
詢問
SELECT pr.project_id, COUNT(DISTINCT pr.keyword_id) as total_keywords, COUNT(CASE WHEN position BETWEEN 4 AND 10 THEN position ELSE NULL END ) AS pos4, date(pr.created_at) AS created_at FROM project_reports pr GROUP BY pr.project_id, date(created_at)
我只想獲取 pos 4-10 中不同的keyword_id 的數量。但是使用我的
SELECT
我得到了所有這些。預期數據範例:
p_id, total_keywords, pos4 1, 3, 3
我目前的數據輸出
p_id, total_keywords, pos4 1, 3, 7
如果您想要不同的關鍵字,那麼您需要計算
keyword_id
,而不是position
列。所以你的表達:
COUNT(CASE WHEN position BETWEEN 4 AND 10 THEN position ELSE NULL END )
變成:
COUNT(distinct CASE WHEN position BETWEEN 4 AND 10 THEN ***keyword_id*** ELSE NULL END )
所以最後的陳述是:
SELECT pr.project_id, COUNT(DISTINCT pr.keyword_id) as total_keywords, count(distinct CASE WHEN position BETWEEN 4 AND 10 THEN keyword_id ELSE NULL END ) AS pos4 FROM project_reports pr GROUP BY pr.project_id;
SQLFiddle 範例:http ://sqlfiddle.com/#!15/b1015/1