[英]Selecting all rows where one field contains the same value
I would like to get the following data out of a table like this: 我想从这样的表中获取以下数据:
Select all rows where User = "Ashley" or User = "Barney"
and SomeID
is equal on both rows. 选择所有行,其中User = "Ashley" or User = "Barney"
并且SomeID
在这两行上均相等。 I basically need to get all customers where Ashley and Barney are listed as salesmen but not only Ashley or only Barney. 我基本上需要获得列出Ashley 和 Barney作为销售员的所有客户,而不仅仅是Ashley或Barney。 Both of them. 他们都。
I have no idea what value SomeID
contains! 我不知道SomeID
包含什么值! The only input I have available is "Ashley" and "Barney". 我唯一可用的输入是“ Ashley”和“ Barney”。
Is there a way to solve this in (Microsoft) SQL? 有没有办法在(Microsoft)SQL中解决此问题? I have tried working with GROUP BY
but it does not really help me. 我曾经尝试过与GROUP BY
一起工作,但这并没有真正帮助我。
To get the IDs, you can use a having-clause with a conditional count for each Salesman value: 要获取ID,您可以对每个Salesman值使用条件条款的条件句:
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
Selecting the entire row is then as easy as joining on this query: 然后,选择整个行就像加入此查询一样容易:
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
I would do it in this way: 我会这样:
SELECT *
FROM MyTable
WHERE SomeID IN (
SELECT SomeID
FROM MyTable
WHERE Salesman IN ('Ashley','Barney')
GROUP BY SomeID
HAVING count(distinct Salesman) = 2
)
Here a demo in SQLFiddle . 这是SQLFiddle中的演示 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.