[英]SQL select all rows with the same ticker where at least one of the rows includes a specific value
[英]SQL - Return all Rows Where at Least one has value 'Y'
我的問題與之前的SQL查詢非常相似, 如果另一列等於x,則獲得一列
唯一的區別是我要聯接兩個表,以前的解決方案似乎不起作用。 基本上,一旦連接了表,我就有兩個列。 我想要一個名稱的所有行,其中至少一個該名稱的行具有“ Shasta”作為位置。 例如,
第1列=名稱(來自表1)第2列=位置(來自表2)
Name | Location
-------------------
Bob | Shasta
Bob | Leaves
Sean | Leaves
Dylan | Shasta
Dylan | Redwood
Dylan | Leaves
應該返回:
Name | Location
--------------------
Bob | Shasta
Bob | Leaves
Dylan | Shasta
Dylan | Redwood
Dylan | Leaves
我嘗試了上一篇文章的解決方案
where x in
(
select distinct x
from table 1
where y like 'Shasta'
)
不幸的是,它只返回了:
Name | Location
--------------------
Bob | Shasta
Dylan | Shasta
您正在尋找WHERE EXISTS
子句。 舉例說明,假設您有以下查詢:
select a.Name, b.Location
from table1 a
join table2 b on a.TableBId = b.Id
您正在尋找檢索該查詢在相同的查詢結果與在那里 存在一個行的所有行Name
和其中Location = 'Shasta'
。 因此,我們可以將查詢用作派生表,匹配Name
並查找Location = 'Shasta'
:
select a.Name, b.Location
from table1 a
join table2 b on a.TableBId = b.Id
where exists (
select 1
from
(
select a.Name, b.Location
from table1 a
join table2 b on a.TableBId = b.Id
) x --this is the same as the above query, as a derived table
where x.Name = a.Name --correlate the queries by matching the Name
and x.Location = 'Shasta' --look for the column value in question
)
當然,您可能能夠簡化此查詢和/或消除WHERE EXISTS
子句中的派生表,具體取決於實際架構以及table1
和table2
代表什么。
我認為您應該執行另一個子查詢。 我稱呼joinedTable
因為您沒有向我們展示構建表的語句。 但是您可以僅將joinedTable
切換為您的語句。 然后做
select * from joinedTable where name in (select name from joinedTable where location = 'Shasta');
結果是您想要的:2x Bob,3x Dylan
這是一個小提琴:
如果存在具有相同名稱和位置Shasta的行,只需使用EXISTS
返回一行:
select name, location
from tablename t1
where exists (select 1 from tablename t2
where t1.name = t2.name
and t2.locaion = 'Shasta')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.