选择一个字段包含相同值的所有行

时间:2014-06-11 14:57:10

标签: sql sql-server

我想从这样的表格中获取以下数据:

Example Table

选择两行中User = "Ashley" or User = "Barney"SomeID相等的所有行。我基本上需要让所有客户将Ashley Barney列为销售人员,但不仅仅是Ashley或Barney。他们两个。

我不知道SomeID包含什么值!我唯一可用的输入是“Ashley”和“Barney”。

有没有办法在(Microsoft)SQL中解决这个问题?我曾尝试使用GROUP BY,但这对我没有帮助。

2 个答案:

答案 0 :(得分:2)

要获取ID,您可以对每个Salesman值使用带有条件计数的having子句:

select SomeID
from MyTable
group by SomeID
having count(case when Salesman = 'Ashley' then 1 else null end) > 0
and count(case when Salesman = 'Barney' then 1 else null end) > 0

选择整行就像加入此查询一样简单:

select MyTable.Customer, MyTable.Salesman, MyTable.SomeID
from MyTable
join (
    select SomeID
    from MyTable
    group by SomeID
    having count(case when Salesman = 'Ashley' then 1 else null end) > 0
    and count(case when Salesman = 'Barney' then 1 else null end) > 0
) x on MyTable.SomeID = x.SomeID

答案 1 :(得分:2)

我会这样做:

SELECT * 
  FROM MyTable
 WHERE SomeID IN (
                   SELECT SomeID
                     FROM MyTable
                    WHERE Salesman IN ('Ashley','Barney')
                 GROUP BY SomeID
                   HAVING count(distinct Salesman) = 2
                 )

这是demo in SQLFiddle