SQL Server查询同一表中的值

时间:2013-08-20 00:59:41

标签: sql sql-server join

我有一个数据表(结构不是很好),其中我有以下

ClientID | Parameter | Value 
111..........Street..........Evergreen
111..........Zip................75244
111..........Country.........USA
222..........Street..........Evergreen
222..........Zip................75244
222..........Country.........USA
333..........Street..........Evergreen
333..........Zip................75240
333..........Country.........USA
444..........Street..........Evergreen
444..........Zip................75240
444..........Country.........USA
555..........Street..........Evergreen
555..........Zip................75240
555..........Country.........USA
666..........Street..........Some Street
666..........Zip................75244
666..........Country.........USA

为此,我想选择Street = Evergreen BUT上的所有客户端ID以及ZIP 75244,我有超过700K的行,所以导出所有这将是一个大问题。

我的想法是:

SELECT ClientID 
from (select ClientID from table1 where Value = 'evergreen')
Where Zip = '75244'

但它不会给我准确的结果在这种情况下我想得到ClientIDs 111和222的值,因为匹配标准我正在寻找Street = Evergreen adn Zip = 75244

有办法做到这一点吗?

3 个答案:

答案 0 :(得分:2)

Select ClientId from MyTable e
inner join MyTable z On e.clientId = z.ClientID
Where e.value = 'Evergreen' and e.Parameter = 'Street'
and z.parameter = 'Zip' and z.Value = '75244'

只需使用带连接的别名,这样就可以“使用你的桌子两次”

答案 1 :(得分:1)

试试这个:

select clientid 
from table1 
where (parameter='Street' and value='Evergreen')
and clientid in (select clientid from table1 where parameter='Zip' and value='75244')

答案 2 :(得分:0)

试试这个

Select e.ClientId from Table1 e
Where e.value in ('Evergreen','75244')
GROUP BY e.ClientId
HAVING count(distinct e.value) = 2