簡體   English   中英

SQL-返回所有行中至少有一個值為“ Y”的行

[英]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子句中的派生表,具體取決於實際架構以及table1table2代表什么。

我認為您應該執行另一個子查詢。 我稱呼joinedTable因為您沒有向我們展示構建表的語句。 但是您可以僅將joinedTable切換為您的語句。 然后做

select * from joinedTable where name in (select name from joinedTable where location = 'Shasta');

結果是您想要的:2x Bob,3x Dylan

這是一個小提琴:

http://sqlfiddle.com/#!9/7584e/3

如果存在具有相同名稱和位置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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM