求 分组统计 sql 语句!!!
本人用的是 sql compact 3.5 ,发现东西支持,现在求 sql 语句,望高手给予指导!
create table t_PhotoVideo
(
pvId int identity,
userId int, -- 不会重复
userName nvarchar(10),
pvType tinyint, --0:图片;1:视频
pvErr tinyint, --0:正常;1:错误
creTime datetime
)
go
insert into t_PhotoVideo values(1,'张三',0,0,'2014-1-1')
insert into t_PhotoVideo values(1,'张三',1,0,'2014-1-2')
insert into t_PhotoVideo values(2,'李四',1,0,'2014-1-1')
insert into t_PhotoVideo values(2,'李四',0,1,'2014-1-2')
insert into t_PhotoVideo values(2,'李四',1,1,'2014-1-2')
insert into t_PhotoVideo values(3,'王五',0,0,'2014-1-3')
求得到下面的结构
-- userId userName 照片数量 视频数量 正常数量 错误数量
-- 1 张三 1 1 2 0
-- 2 李四 1 2 1 2
-- 3 王五 1 0 1 0
[解决办法]
不知道CE支不支持
--create table t_PhotoVideo
--(
-- pvId int identity,
-- userId int, -- 不会重复
-- userName nvarchar(10),
-- pvType tinyint, --0:图片;1:视频
-- pvErr tinyint, --0:正常;1:错误
-- creTime datetime
--)
--go
--insert into t_PhotoVideo values(1,'张三',0,0,'2014-1-1')
--insert into t_PhotoVideo values(1,'张三',1,0,'2014-1-2')
--insert into t_PhotoVideo values(2,'李四',1,0,'2014-1-1')
--insert into t_PhotoVideo values(2,'李四',0,1,'2014-1-2')
--insert into t_PhotoVideo values(2,'李四',1,1,'2014-1-2')
--insert into t_PhotoVideo values(3,'王五',0,0,'2014-1-3')
SELECT userid,username,COUNT(CASE WHEN pvType=0 THEN 1 ELSE NULL END )[照片数量],
COUNT(CASE WHEN pvType=1 THEN 1 ELSE NULL END )[视频数量],
COUNT(CASE WHEN pvErr=0 THEN 1 ELSE NULL END )[正常数量],
COUNT(CASE WHEN pvErr=1 THEN 1 ELSE NULL END )[错误数量]
FROM t_PhotoVideo
GROUP BY userid,username
ORDER BY userid
/*
userid username 照片数量 视频数量 正常数量 错误数量
----------- ---------- ----------- ----------- ----------- -----------
1 张三 1 1 2 0
2 李四 1 2 1 2
3 王五 1 0 1 0
*/
select a.userId,a.userName,
(select count(1) from t_PhotoVideo b
where b.userId=a.userId and b.userName=a.userName and b.pvType=0) '照片数量',
(select count(1) from t_PhotoVideo b
where b.userId=a.userId and b.userName=a.userName and b.pvType=1) '视频数量',
(select count(1) from t_PhotoVideo b
where b.userId=a.userId and b.userName=a.userName and b.pvErr=0) '正常数量',
(select count(1) from t_PhotoVideo b
where b.userId=a.userId and b.userName=a.userName and b.pvErr=1) '错误数量'
from t_PhotoVideo a
group by a.userId,a.userName
/*
userId userName 照片数量 视频数量 正常数量 错误数量
----------- ---------- ----------- ----------- ----------- -----------
1 张三 1 1 2 0
2 李四 1 2 1 2
3 王五 1 0 1 0
(3 row(s) affected)
*/