SQL - 返回所有行,其中至少有一行有价值' Y'

时间:2015-05-29 04:07:10

标签: sql distinct

我的问题与上一篇文章非常相似 SQL Query, get a columns if another columns equal to 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

3 个答案:

答案 0 :(得分:1)

您正在寻找WHERE EXISTS条款。作为示例,我们假设您有以下查询:

select a.Name, b.Location
from table1 a
join table2 b on a.TableBId = b.Id

您希望检索此查询中的所有行 存在Name相同的查询结果中的行和{{1} }。因此,我们可以将查询用作派生表,匹配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 EXISTStable1代表的内容。< / p>

答案 1 :(得分:0)

我认为你应该做另一个子查询。我将调用joinresult 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

答案 2 :(得分:0)

如果存在具有相同名称和位置的行,只需使用select name, location from tablename t1 where exists (select 1 from tablename t2 where t1.name = t2.name and t2.locaion = 'Shasta') 返回一行Shasta:

Dim conn As New ServerConnection("NPSS-OJT", "sa", "rms")
        Dim srv As New Server(conn)
        Dim db As Database = srv.Databases("bos_primary_db")
        Dim dbCopy As Database = New Database(srv, Main.dbName)

        Dim xfr As Transfer
        xfr = New Transfer(db)
        xfr.CopyAllTables = True
        xfr.Options.WithDependencies = True
        xfr.Options.ContinueScriptingOnError = True
        xfr.DestinationDatabase = dbCopy.Name
        xfr.DestinationServer = srv.Name
        xfr.DestinationLoginSecure = True
        xfr.CopySchema = True
        xfr.CopyData = True

        xfr.TransferData()