請注意,對於示例表,我添加了一個basket_id = 4的籃子,它只有兩個蘋果,它將成爲查詢的強大測試樣本。
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
爲什麼不是籃子3還這個basket_id也有兩個特定的水果? –
第二排只意味着什麼?你會包括第一次進入蘋果和橘子嗎? – Harsh