简体   繁体   中英

SQL Server - Select distinct Query

I have a tblA where I have a few thousand clients. I'm trying to write a query that would show me clients that have more than one record of a certain type. This is what my table looks like.

ClientID          TypeB
123               1
145               1
123               2
199               1
199               2
145               2
123               1

So as you can see here (this is not a complete table, but this is only relevant). Each client is supposed to only have one record for TypeB=1 and TypeB=2. Some clients however(123) has more than one record for TypeB=1. I'm trying to find all clients that have more than one record of Type=1.

Desired end result:

ClientID           TypeB
123                1
123                1

This is what I've been trying to do

 select distinct(clientid), TypeB
 from tblA 
 where TypeB=1
 having count(TypeB)>1
 group by clientid

Try to use

SELECT a.clientid, 
       a.typeb 
FROM   tblA  a 
WHERE  (SELECT Count(*) 
        FROM   tblA  b 
        WHERE  b.clientid = a.clientid 
               AND b.typeb = 1) > 1 

See if it works in sql server:

select *
from client
qualify sum()over(partition by clientId, typeB)>1

other easy way is

select *
from client
where clientId in 
(select clientId 
from client
having count(*)>1)

You can try this

;with cte as (
select clientid, typeb, row_number() over(partition by clientid, typeb order by clientid) as rn
from yourtable ) select clientid, typeb from cte where rn > 1

I'm thinking you need something like this

SELECT COUNT(ClientID), ClientID, TypeB
FROM tblA
WHERE TypeB = 1
GROUP BY ClientID, TypeB
HAVING COUNT(ClientID) > 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