日期:2014-05-19  浏览次数:20510 次

一个group by 和distinct联合使用的问题?
显假设表有两列:
user         value
-----------
a                         1
a                         2
a                         3
a                         3
a                         2
b                         1
b                         1
b                         2
......
现在需要求与每个user有多少不同的value。
例如,user   a的value有多少种,从表中可以看到1、2、3三种value...

这个问题应该怎么来解决呢?
谢谢!

------解决方案--------------------
create table #a(
[user] varchar(10),
value int
)

insert into #a
select 'a ',1 union all
select 'a ',2 union all
select 'a ',3 union all
select 'a ',1 union all
select 'b ',1 union all
select 'b ',1 union all
select 'b ',2

select [user],count(distinct value) 种数
from #a
group by [user]

----------------
a 3
b 2

------解决方案--------------------
请LZ看下面的“结果1”和“结果2”,哪一个是你所需要的?
create table a5(
[user] varchar(10),
value int
)
go
insert into a5
select 'a ',1 union all
select 'a ',2 union all
select 'a ',3 union all
select 'a ',1 union all
select 'b ',1 union all
select 'b ',1 union all
select 'b ',2 union all
select 'b ',2 union all
select 'b ',3 union all
select 'b ',4
go
----------------
结果1:
select distinct [user],value
from a5
----------------
结果2:
select [user],count(distinct value) distinctvaluenumber
from a5
group by [user]