I have the following data:
id user_id typecode
-----------------------------------
10 123 'TypeA'
11 123 'TypeB'
12 124 'TypeA'
13 124 'TypeA'
14 125 'TypeA'
15 125 'TypeB'
16 125 'TypeB'
17 125 'TypeA'
I need a query that will return user_ids for users that have more than 1 'TYPEA' and/or more than 1 'TypeB'. (124, 125)
This is using SQL Server 2008.
SELECT DISTINCT user_id FROM table WHERE typecode = 'TypeA' OR typecode = 'TypeB'
GROUP BY user_id, typecode HAVING COUNT(typecode) > 1
I edited the query to take int to account that only TypeA or TypeB are of interest. Bum not exactly sure about this. This might return user two tiems if it hase 2 TypeA and 2 TypeB ie
This is a perfect use case for the union
clause.
The query below returns all users ids that have more than 1 TypeA
plus all users ids that have more than 1 TypeB
.
-- all user_ids that have more than one TypeA
select user_id
from yourTable
where typecode = 'TypeA'
group by user_id
having count(*) > 1
union
-- all user_ids that have more than one TypeB
select user_id
from yourTable
where typecode = 'TypeB'
group by user_id
having count(*) > 1
This query satisfies your and/or
requirement, ie, it selects:
The beauty of union
is that there is no need make a select distinct user_id
, since union
merges the result sets into unique values
Try this:
SELECT *
FROM
(
SELECT user_id,
SUM(CASE typecode WHEN 'TypeA' THEN 1 ELSE 0 END) TypeACount,
SUM(CASE typecode WHEN 'TypeB' THEN 1 ELSE 0 END) TypeBCount
FROM <YOUR-TABLE> a
GROUP BY user_id
) a
WHERE a.TypeACount > 1 OR a.TypeBCount > 1
select user_id
from YourTable
group by user_id
having count(case typecode when 'TypeA' then 1 end) > 1 or
count(case typecode when 'TypeB' then 1 end) > 1
SELECT user_id
FROM users
GROUP BY user_id, typecode
HAVING COUNT(id) > 1
something like this maybe:
select user_id, count(typecode) as t_count
group by user_id
where t_count > 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.