繁体   English   中英

如何返回一种以上类型的行?

[英]How do I return rows where there is more than one type?

我有以下数据:

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_id。 (124,125)

这正在使用SQL Server 2008。

SELECT DISTINCT user_id FROM table WHERE typecode = 'TypeA' OR typecode = 'TypeB' 
   GROUP BY user_id, typecode HAVING COUNT(typecode) > 1

我编辑查询以考虑到只有TypeA或TypeB是有意义的。 屁股不是很确定。 如果它具有2个TypeA和2个TypeB,则可能会返回两个tiems,即

这是union子句的完美用例。

以下查询返回TypeA大于1的所有用户ID以及TypeB大于1的所有用户ID。

-- 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要求,即选择:

  • 所有类型A超过1的用户或
  • 所有拥有1个以上B型用户或
  • 所有类型A超过1和类型B超过的用户

union在于,无需select distinct user_id唯一的select distinct user_id ,因为union将结果集合并为唯一值

尝试这个:

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  

可能是这样的:

select user_id, count(typecode) as t_count
group by user_id
where t_count > 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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