每周计算一次,考虑到已删除的日期

时间:2014-07-29 04:48:50

标签: mysql

ID  |Created_Date|  Modified_date|  Deleted(YN) 
1   |01-01-2014 |   NULL         |     0    
2   |01-03-2014 |   NULL         |     0    
3   |01-04-2014 |01-11-2014      |     1    
4   |01-05-2014 |01-12-2014      |     1    
5   |01-08-2014 |01-17-2014      |     1    
6   |01-09-2014 |   NULL         |     0   
7   |01-20-2014 |   NULL         |     0   

我需要每周计算一次,考虑到特定周内删除的那些。例如, 如果12-29-2013 - 01-04-2014被视为第1周且01-05-2014 - 01-11-2014被视为第2周,则输出应如下所示:

|Date       | count|
|12-29-2013 | 3
|01-04-2014 | 5 (this is because on 11th, there is a deleted record)

查询如下:

select date_add(created_date, interval(1-DAYOFWEEK(created_date)) DAY)
created_date, count(*) from table1 where 
(date_add(created_date, interval(7-DAYOFWEEK(created_date)) DAY) and deleted=0)
or (deleted = 1 and  modified_date > 
DATE_ADD(created_date, INTERVAL(7-DAYOFWEEK(created_date)) DAY)) 
group by week(created_date)

问题是,它没有考虑前几周删除的数据而没有给出总计数 - 删除计数。请帮助替代方案。

2 个答案:

答案 0 :(得分:1)

使用WEEK()功能,您的查询将类似于

SELECT WEEK(created_date) as W, 
  COUNT(*) as All, 
  SUM(deleted*SIGN(WEEK(Modified_date)-W)) as Deleted, 
  All - Deleted as Real
FROM table1 
WHERE created_date>='2014-01-01'
GROUP BY W
ORDER BY W;

此外,如果您计划使用此查询获得超过一年的结果,则必须使用YEARWEEK()代替WEEK()

查询未经过测试,希望无需修改

评论5的更新:

SELECT WEEK(created,1) W, 
  COUNT(*) AllCount, 
  n.c
FROM table1
LEFT JOIN 
  (SELECT 
     WEEK(modified,1) m, 
     count(*) c 
  FROM table1 WHERE isdeleted=1 GROUP BY WEEK(modified,1)) n 
  ON WEEK(created,1)=n.m
WHERE created>='2014-01-01'
GROUP BY WEEK(created,1)
ORDER BY WEEK(created,1);

SQL小提琴here

答案 1 :(得分:0)

Query edited to cover the modified ones/deleted ones which are not falling in created weeks. Please let me know, if this can be simplified more. If not, this seems one way to achieve.

SELECT DISTINCT * FROM(
SELECT date_add(created_date, interval(1-DAYOFWEEK(created_date)) DAY)   W,     
  count(*) AllCount, 
  n.c
FROM table1
left JOIN 
  (SELECT 
     WEEK(modified_date,1) m, 
     count(*) c 
  FROM table1 where deleted=1 GROUP BY WEEK(modified_date,1)) n 
  ON WEEK(created_date,1)=n.m
GROUP BY WEEK(created_date,1) 
UNION ALL
SELECT date_add(MODIFIED_date, interval(1-DAYOFWEEK(MODIFIED_date)) DAY)   W,   
  n.c as ALLCount,
  count(*) Deleted 
FROM table1
left JOIN 
  (SELECT 
     WEEK(CREATED_date,1) m, 
     count(*) c 
  FROM table1  GROUP BY WEEK(CREATED_date,1)) n 
  ON WEEK(MODIFIED_date,1)=n.m
WHERE DELETED=1
GROUP BY WEEK(MODIFIED_date,1) ) x
ORDER BY W