簡體   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