2017-11-30 3 views
0
select distinct(msg_id),sub_id from programs where sub_id IN 
(
select sub_id from programs group by sub_id having count(sub_id) = 2 limit 5 
) 

sub_idはあるセレクトレコードだけは - サブスクライバのpostgresに二回

インナークエリは、番組表に正確に2倍であるこれら - サブスクライバを返し、メイン・クエリの意志が明確なMSG_IDを有するもの - サブスクライバを与える意味します。

この結果は、私はそれがあるべきたく

msg_id sub_id 
------|--------| 
112 | 313 
111 | 222 
113 | 313 
115 | 112 
116 | 112 
117 | 101 
118 | 115 
119 | 115 
110 | 222 

を生成します

msg_id sub_id 
    ------|--------| 
    112 | 313 
    111 | 222 
    113 | 313 
    115 | 112 
    116 | 112 
    118 | 115 
    119 | 115 
    110 | 222 

117 | 101(この結果は一度だけ出力されるべきではありません)

私は2回のレコードしか欲しません。

+1

ポストサンプルデータ –

+0

を試してみてください、私はすでに私は、クエリから得たデータを掲載しました。あなたはこれ以外に何をしたいですか? –

+0

クエリの出力を投稿しました。入力データを転記します。 –

答えて

0

私はよく分かりませんが、あなたのリストに2番目のフィールドがありませんか?

select distinct msg_id, sub_id, <presumably other fields> 
from programs 
where (sub_id, msg_id) IN 
(
    select sub_id, msg_id 
    from programs 
    group by sub_id, msg_id 
    having count(sub_id) = 2 
) 

もしそうなら、あなたはまた、ウィンドウ関数でこれを行うことができます。

with cte as (
    select 
    msg_id, sub_id, <presumably other fields>, 
    count (*) over (partition by msg_id, sub_id) as cnt 
    from programs 
) 
select distinct 
    msg_id, sub_id, <presumably other fields> 
from cte 
where cnt = 2 
+0

いいえ、動作しません。私は質問があなたにあまり明確ではないと思う –

0

この

SELECT msg_id, MAX(sub_id) 
FROM programs 
GROUP BY msg_id 
HAVING COUNT(sub_id) = 2 -- COUNT(sub_id) > 1 if you want all those that repeat more than once 
ORDER BY msg_id