日期:2014-05-18  浏览次数:20645 次

sql统计问题!
如保统计出一个表中
如 aa表
 id         user_Id       class_Id
    1               20                   10
    2               20                   10
    3               20                   20  
    4               30                   20

select   count(*)   as   n   where   user_id=20
统计出 user_id=20   有多少条记录(但class_id不能有重复的)
统计结果应为 n=2

------解决方案--------------------
select class_Id,count(user_id) as n where user_id=20 group by class_Id,user_id

------解决方案--------------------
看错了,不好意思,不是这样~

------解决方案--------------------
select class_Id,count(*) as n where user_id=20 group by class_Id,user_id
------解决方案--------------------
select count(user_Id) from
(
select user_Id,class_Id from tb group by user_Id,class_Id
)a
where user_Id=20
------解决方案--------------------

create table tb(id int,user_Id int,class_Id int)
insert tb select 1,20,10
union all select 2,20,10
union all select 3,20,20
union all select 4,30,20

select count(user_Id) from
(
select user_Id,class_Id from tb group by user_Id,class_Id
)a
where user_Id=20


-----------
2

(所影响的行数为 1 行)
------解决方案--------------------
id user_Id class_Id
1 20 10
2 20 10
3 20 20
4 30 20

select count(*) as n from (
select distinct class_Id,user_id from 表 where user_id=20 ) a
------解决方案--------------------
select count(distinct(class_id)) from aa where user_id=20
------解决方案--------------------
换一角度考虑就是统计user_id=20的不重复的class_Id的个数。

------解决方案--------------------
create table tb(id int,user_td int,class_Id int)
insert tb select 1,20,10
union all select 2,20,10
union all select 3,20,20
union all select 4,30,20

select count(*) from (select distinct user_td from tb) w


------解决方案--------------------
select count(distinct(class_id)) as n from aa where user_id=20