你並不需要加入t1
,你需要COUNT(DISTINCT column_name)
:
SQL Fiddle
的Oracle 11g R2架構設置:
CREATE TABLE t2 (ID, T1_ID, Value) AS
SELECT 1, 1, 'Apple' FROM DUAL UNION ALL
SELECT 2, 1, 'Orange' FROM DUAL UNION ALL
SELECT 3, 1, 'Kiwi' FROM DUAL UNION ALL
SELECT 4, 2, 'Orange' FROM DUAL UNION ALL
SELECT 5, 2, 'Kiwi' FROM DUAL UNION ALL
SELECT 6, 3, 'Pear' FROM DUAL UNION ALL
SELECT 7, 3, 'Berry' FROM DUAL UNION ALL
SELECT 8, 3, 'Orange' FROM DUAL UNION ALL
SELECT 9, 4, 'Apple' FROM DUAL UNION ALL
SELECT 10, 5, 'Apple' FROM DUAL UNION ALL
SELECT 11, 5, 'Apple' FROM DUAL UNION ALL
SELECT 12, 5, 'Kiwi' FROM DUAL;
查詢1:
select t1_id,
LISTAGG(value, ',') WITHIN GROUP (ORDER BY value) As "values"
from t2
where value in ('Apple','Orange','Kiwi')
group by t1_id
having count(DISTINCT value) = 3
Results:
| T1_ID | values |
|-------|-------------------|
| 1 | Apple,Kiwi,Orange |
查詢2:
您也可以使用集合做到這一點:
CREATE TYPE STRINGLIST IS TABLE OF VARCHAR2(10);
/
SELECT *
FROM (
SELECT t1_id,
CAST(COLLECT(value ORDER BY value) AS STRINGLIST) AS "values"
FROM t2
GROUP BY t1_id
)
WHERE STRINGLIST('Apple', 'Kiwi', 'Orange') SUBMULTISET OF "values"
Results:
| T1_ID | values |
|-------|-------------------|
| 1 | Apple,Kiwi,Orange |
我們如何知道查詢是否正確?你發佈輸入(完美!)和一些代碼,顯然不會做你想做的(也很有幫助)。你沒有說明要求。你需要返回什麼?所有的原始行,僅適用於與Apple,Orange和Kiwi一起出現的T1_ID至少一次?正好一次?究竟是那三個而不是其他?所有這些可能的解釋都與你發佈的內容一致。那麼:什麼是要求? – mathguy
@mathguy:所有Apple,Orange和Kiwi,3個值至少一次。我的問題是從我當前的查詢,如果我做了一個值= 3,它不起作用,因爲一些記錄可能有重複,例如:ID = 5。 – Skn