简体   繁体   中英

Select Grouped Column Values Where Have Same Id In SQL Server

I have a table like this.

TABLE-1

   id         Code
   -----------------
   1          N188
   1          N1Z2
   1          N222
   2          N189
   2          N1Z2
   2          N1Z3
   3          N188
   3          A123
   3          B321
   4          N188
   4          A333
   4          B444

I want to select id and code only code has N188 .Result should like this:

TABLE-2

 id         Code
 ---------------
 1          N188
 1          N1Z2
 1          N222
 3          N188
 3          A123
 3          B321
 4          N188
 4          A333
 4          B444

How can I write sql for this in SQL Server?

Thanks

You can use EXISTS for this:

SELECT id, code
FROM table1 t
WHERE EXISTS (
    SELECT 1
    FROM table1 t2
    WHERE t.id = t2.id
        AND t2.Code = 'N188'
)

Using INNER JOIN

SELECT *
FROM   tablename A
       JOIN (SELECT id
             FROM   tablename
             WHERE  code = 'N188') B
         ON a.id = b.id 

Here is an alternative method that uses window functions:

select id, code
from (select t.*,
             sum(case when code = 'N188' then 1 else 0 end) over (partition by id) as cnt_n188
      from table t
     ) t
where cnt_n188 > 0;

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