![](/img/trans.png)
[英]SQL SELECT Values from column in one table to a column in another table in order (one by one)
[英]Select only values from one column in a table in SQL with condition
是否有可能只獲得剛剛參加預賽的國家
Country Round
Germany Pre Round
Germany Quater final
Spain Pre Round
Portugal Pre Round
而且我只想獲得只參加預賽的國家。 所以結果應該是這樣的:
Country
Spain
Portugal
您可以group by country
並在have子句中設置條件:
select country
from tablename
group by country
having count(*) = 1 and max(round) = 'Pre Round'
您可以嘗試以下使用not exists
select country from c
where not exists
(select 1 from c as c1 where c.country=c1.country and roundval<>'Pre Round')
還有兩個好玩。 第一種是@forpas' 的一種變體,為每一輪分配一個數值,表示每輪的進度,然后獲得該國家/地區的最高值(如果輪數與輪數分開存儲會更簡單):
select country
from your_table
group by country
having max(case round
when 'Pre Round' then 1
when 'Quater final' then 2
when 'Semi final' then 3
when 'Final' then 4
end) = 1;
如果您想查找處於四分之一但不是半決賽的國家/地區,那么您只需更改為= 2
等。
第二個在這里是多余的,但對於在其他類型的數據中尋找更復雜的組合可能很有用:
select country
from your_table
pivot (
count(*) for round in (
'Pre Round' as pre, 'Quater final' as quarter, 'Semi final' as semi, 'Final' as final
)
)
where pre = 1 and quarter = 0 and semi = 0 and final = 0;
顯然,在您的示例中,您永遠不會將四分之一設為 0,然后將半決賽或決賽設為 1 - 如果不打四分之一,您將無法進入這些回合; 但對於其他數據,您可能需要混合。
您可以在子查詢中使用內部連接來查詢國家的圓形're Round'並檢查不同的計數
select m.Contry
from my_table m
inner join (
select Country
from my_table
where round ='Pre Round'
) t on t.country = m.country
group by m.Country
having count(distinct m.round ) = 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.