以下2つのテーブルで、それぞれ以下4つを抽出したいのですがうまくいきません。。
①mstテーブルのうち、purchaseのflagが1のみの人数
②mstテーブルのうち、purchaseのflagが2のみの人数
③mstテーブルのうち、purchaseのflag1と2両方存在する人数
④mstテーブルのみに存在する人数(purchaseテーブルにいない)
■テーブル:mst
uid
1111
2222
3333
■テーブル:purchase
uid flag
1111 1
1111 2
2222 1
3333 1
3333 2
4444 2
たとえば①の答えは
uid「1111」は1,2とも存在するので対象外で、対象はuid「2222」のみなので回答は「1」としたいです。
①と②は以下で出るかと思ったのですが、データが0となってしまいます、、
SQL
1select 2 count(distinct case when flag = '1' then a.uid else null end) as one_only 3 count(distinct case when flag = '2' then a.uid else null end) as two_only 4from( 5select 6 uid 7from mst 8GROUP BY 1 ) as a 9 10left join ( 11 select 12 uid, 13 flag 14 from purchase 15 GROUP BY 1,2 ) as b on a.uid = b.uid 16 17HAVING COUNT(distinct flag)= 1 18
あなたの回答
tips
プレビュー