日期:2014-05-18 浏览次数:20476 次
IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE name = 'logtable') BEGIN DROP TABLE logtable END GO CREATE TABLE logtable ( id INT, userid INT, actdate VARCHAR(10), Doaction INT ) GO INSERT INTO logtable SELECT 1,1,'2012-05-07',1 UNION SELECT 2,1,'2012-05-07',0 UNION SELECT 3,1,'2012-05-07',1 UNION SELECT 4,1,'2012-05-08',1 UNION SELECT 5,1,'2012-05-09',1 UNION SELECT 6,2,'2012-05-07',1 UNION SELECT 7,2,'2012-05-08',1 UNION SELECT 8,2,'2012-05-08',1 UNION SELECT 9,2,'2012-05-09',1 UNION SELECT 10,2,'2012-05-09',1 UNION SELECT 11,2,'2012-05-09',1 select userid,actdate, SUM(case when Doaction=1 then 1 else 0 end) as times from logtable where actdate<=getdate()--得到系统当前日期 group by userid,actdate order by userid,actdate /* userid actdate times 1 2012-05-07 2 1 2012-05-08 1 2 2012-05-07 1 2 2012-05-08 2 */ 借楼上测试数据一用。 我觉得你的统计结果存在问题 SELECT 1,1,'2012-05-07',1 UNION--有这一行数据存在 1 2012-05-07 0--这一行不对 希望解释一下,是我没明白楼主的意思还是怎么的。谢谢了
------解决方案--------------------
select *,(count(*) from log where userid=a.userid and [date]<a.[date] and action=1) from log a where [date] <'2012-05-01'
------解决方案--------------------
IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE name = 'logtable') BEGIN DROP TABLE logtable END GO CREATE TABLE logtable ( id INT, userid INT, actdate VARCHAR(10), Doaction INT ) GO INSERT INTO logtable SELECT 1,1,'2012-05-07',1 UNION SELECT 2,1,'2012-05-07',0 UNION SELECT 3,1,'2012-05-07',1 UNION SELECT 4,1,'2012-05-08',1 UNION SELECT 5,1,'2012-05-09',1 UNION SELECT 6,2,'2012-05-07',1 UNION SELECT 7,2,'2012-05-08',1 UNION SELECT 8,2,'2012-05-08',1 UNION SELECT 9,2,'2012-05-09',1 UNION SELECT 10,2,'2012-05-09',1 UNION SELECT 11,2,'2012-05-09',1 --5月7日之前,不包括当日 SELECT DISTINCT actdate,CASE WHEN (SELECT SUM(Doaction) FROM logtable AS B WHERE A.actdate > B.actdate) IS NULL THEN 0 ELSE (SELECT SUM(Doaction) FROM logtable AS B WHERE A.actdate > B.actdate) END AS 操作次数 FROM logtable AS A actdate 操作次数 2012-05-07 0 2012-05-08 3 2012-05-09 6 --5月7日之前,包括当日 SELECT DISTINCT actdate,CASE WHEN (SELECT SUM(Doaction) FROM logtable AS B WHERE A.actdate >= B.actdate) IS NULL THEN 0 ELSE (SELECT SUM(Doaction) FROM logtable AS B WHERE A.actdate >= B.actdate) END AS 操作次数 FROM logtable AS A actdate 操作次数 2012-05-07 3 2012-05-08 6 2012-05-09 10