基本上,我想讓結果顯示列c的任何實體,其中列h等于'h1' 和'h2'。
我試著使用IN運算子,但它顯示任何列c的實體,其中列h等于'h1'或'h2'
這是我目前所擁有的:
這是我目前所擁有的。
select a, b, c, d, e, f, g, h, i
from table t
inner join table2 t2 on t.c = t2.c
inner join table3 t3 on t3.f = t2.f
inner join table4 t4 on t4.b= t.b
-- note: a,c,h是問題列,其他都是額外資訊。
where e = e1
and h in (h1, h2)
and c not in (select cfrom table t where (h = h1 and i = i0)
order by h asc
而結果(只包括相關的列)被回傳為:
a c h
----------
a1 c1 h1
a1 c1 h1
a2 c2 h2
a2 c2 h2
a3 c3 h1
a3 c3 h2
但是我想讓它只得到這樣的結果:
a c h
----------
a3 c3 h1
a3 c3 h2
編輯:我將簡化這個問題并使用一個例子,希望這更有意義
基本上,我希望結果顯示列Pet Shop的任何實體,其中列Animal等于'Cat' 和'Dog'。
我試著使用IN運算子,但它顯示了列Pet Shop的任何實體,其中列Animal等于'Cat' 或'Dog'
這是我目前所掌握的情況:
select * from table t
where Animal in (Cat, Dog)
訂購 由寵物店asc提供
并且回傳的結果是:
Pet Shop Animal
-------------------
狗狗大作戰1。
Dogs Galore 狗 2
貓的天堂 貓 1
Cat Galore 貓 2
寵物 'r' 我們狗 3
寵物 'r'我們的貓 3
但我希望它只得到這樣的結果:
寵物店動物
-------------------
寵物 'r' 我們的狗 3
寵物'r'我們的貓3。
因為它是唯一一家既有貓又有狗的寵物店
。
uj5u.com熱心網友回復:
你有一個結果集,但你只想顯示其中的行,對于a和c這一對,同時存在h='h1'和h='h2'的行。做到這一點的一個方法是在分析函式中使用條件聚合:
select a, b, c, d, e, f, g, h, i
from
(
select
a, b, c, d, e, f, g, h, i。
case when
count(case when h = 'h1' then 1 end) over (partition by a, c) >/span> 0 and
count(case when h = 'h2' then 1 end) over (partition by a, c) > 0
then 'yes'/span> else 'no'/span> end as both_exist
from table t
inner join table2 t2 on t.c = t2.c
inner join table3 t3 on t3.f = t2.f
inner join table4 t4 on t4.b= t.b
where e = 'e1'/span>
and h in ('h1', 'h2')
and c not in (select c from table t where (h = 'h1' and i = 'i0')
) 檢查
where both_exist = 'yes'/span>
order by a, c, h;
(免責宣告:我沒有真正研究過你的查詢,而是照單全收。我只是添加了 both_exists 運算式,這應該是你所需要的。
uj5u.com熱心網友回復:
首先,我們將使用 cte 洗掉重復的內容。在洗掉重復的資料后,我們將與h值大于2的表進行連接。
; WITH CTE AS (
SELECT DISTINCT * FROM sample)
SELECTS.*
from CTE S
INNER JOIN (SELECT a, c FROM CTE WHERE h in ('h1'/span>, 'h2') group by a, c having count(*)> =2)T1 ON T1. a= S.a AND T1.c = S.C;
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/311056.html
標籤:
上一篇:如何為同一表中的某一列做外鍵參考
