简体   繁体   中英

How to select in SQL Server 2008

Have an issue

Examle

ID      ID2

1       100  

3       100

5       100

1       110

2       110

4       110




select * from table where ID in (1,4) ---executing not correctly

select * from table where ID = '1' and ID = '4' ---not work

I need that ID2 will '110' (select ID2 which have 2 value ID)

Thanks.

If you have few ID's you can use EXISTS :

SELECT ID, ID2
FROM dbo.Table1 t1
WHERE EXISTS
(
   SELECT 1 FROM dbo.Table1 t2 
   WHERE t2.ID=1 AND t2.ID2=t1.ID2
)
AND EXISTS
(
   SELECT 1 FROM dbo.Table1 t2 
   WHERE t2.ID=4 AND t2.ID2=t1.ID2
)
AND ID IN (1, 4)

This returns the two records that have the same ID2 and ID=1 AND ID=4.

ID  ID2
1   110
4   110

Demo-Fiddle

SELECT ID FROM (
SELECT ID, COUNT(*) OVER(PARTITION BY ID2) as cnt FROM Table) t
WHERE t.cnt>1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM