开发者

Tricky sql to select distinct user

given the following data/tabel:

User|Value
A 1
A 1
B 3
B 1
A 1
A 3
A 3
B 1
B 1
A 1
B 1 
B 1
A 3
A 3
B 1

Here I want to pick out those users who 开发者_高级运维have alternated the Value column more than once. Eg. Here B is not a problem as it changes only once, A on the other hand changes often and I want a sql select that returns A.

I have not found any examples on how to do this! :(


I think this should work:

SELECT DISTINCT u1.UserName
FROM Users u1
INNER JOIN Users u2 ON u1.UserName = u2.UserName
INNER JOIN Users u3 ON u1.UserName = u3.UserName
WHERE u1.Value <> u2.Value
AND u1.UserID < u2.UserID
AND u2.Value <> u3.Value
AND u2.UserID < u3.UserID

Assuming your table is called "Users", of course :)


declare @t table(user_id char(1), val tinyint)

insert into @t
select 'A', 1
union all
select 'A', 1
union all
select 'B', 3
union all
select 'B', 1
union all
select 'A', 1
union all
select 'A', 3
union all
select 'A', 2
union all
select 'A', 1
union all
select 'B', 1
union all
select 'B', 1
union all
select 'A', 1

select user_id, count(distinct val)
from @t
group by user_id
having count(distinct val) > 2
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜