首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

sql统计有关问题

2012-01-19 
sql统计问题!如保统计出一个表中如 aa表 iduser_Idclass_Id12010220103202043020selectcount(*)asnwhereus

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

热点排行