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

新手继续提问sql
一张log表字段如下:
id | user_id | date | action

action值可为0或者1
每日每用户可有多次action

要统计的是每日,在那日之前一共有多少次action为1的操作

比如 2012-05-01之前一共有多少次action为1的操作,我会算每天的,不会算每天之前的总和。

希望各位高手指教

------解决方案--------------------
SQL code


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--这一行不对

希望解释一下,是我没明白楼主的意思还是怎么的。谢谢了

------解决方案--------------------
SQL code
select *,(count(*) from log where userid=a.userid and [date]<a.[date] and action=1)
 from log a where [date] <'2012-05-01'

------解决方案--------------------
SQL code


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