![](/img/trans.png)
[英]MySQL query returns more rows than intended, how do i only return the highest value of one column from each group?
[英]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
要求,即選擇:
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.