例の表に注意してください。basket_id = 4のバスケットをもう1つ追加しました。これは2つのリンゴのみを持ち、クエリの強力なテストサンプルになります。
WITH ABC --sample table
AS
(
SELECT 1 as basket_id, 'Apple' as fruit
UNION ALL
SELECT 1 as basket_id, 'Orange' as fruit
UNION ALL
SELECT 1 as basket_id, 'Pear' as fruit
UNION ALL
SELECT 2 as basket_id, 'Apple' as fruit
UNION ALL
SELECT 2 as basket_id, 'Orange' as fruit
UNION ALL
SELECT 3 as basket_id, 'Apple' as fruit
UNION ALL
SELECT 3 as basket_id, 'Pear' as fruit
UNION ALL
SELECT 4 as basket_id, 'Apple' as fruit
UNION ALL
SELECT 4 as basket_id, 'Apple' as fruit
)
--main query:
SELECT basket_id FROM
(
SELECT *,CASE WHEN fruit in ('Apple','Orange') THEN 1 ELSE 0 END AS row_check
FROM ABC
) as A
GROUP BY basket_id
HAVING COUNT(DISTINCT row_check) =1 -- make sure there is no other fruit
AND COUNT(DISTINCT fruit) >1 -- make sure there are at least one apple and one orange
出力:ここbasket_id 2
なぜbasket_idもこのbasket_idには2つの特定の果物がありますか? –
2番目の行のみを意味しますか?あなたはリンゴとオレンジの最初のエントリを含めるだろうか? – Harsh