我有以下数据:
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'
我需要一个查询,它会为超过1'TYPEA'和/或超过1'TypeB'的用户返回user_ids。 (124,125)
这是使用SQL Server 2008。
答案 0 :(得分:3)
SELECT DISTINCT user_id FROM table WHERE typecode = 'TypeA' OR typecode = 'TypeB'
GROUP BY user_id, typecode HAVING COUNT(typecode) > 1
我编辑了查询以将int视为仅对TypeA或TypeB感兴趣的帐户。嗯不完全确定这一点。如果它有2个TypeA和2个TypeB,即
,这可能会返回用户两个tiems答案 1 :(得分:3)
这是union
子句的完美用例。
以下查询会返回超过1 TypeA
的所有用户ID
加上所有用户ID超过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
此查询满足您的and/or
要求,即选择:
union
的美妙之处在于无需制作select distinct user_id
,因为union
将结果集合并为唯一值
答案 2 :(得分:1)
试试这个:
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
答案 3 :(得分: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
答案 4 :(得分:0)
SELECT user_id
FROM users
GROUP BY user_id, typecode
HAVING COUNT(id) > 1
答案 5 :(得分:-1)
这样的事情可能是:
select user_id, count(typecode) as t_count
group by user_id
where t_count > 1