我正在尝试获取过去7天的日期和总和(总计)。我正在尝试此代码并获取日期NULL和daily_sale 0.00
SELECT
date,
IFNULL( SUM( total ), 0 ) AS daily_sale
FROM sales
WHERE date BETWEEN NOW()
AND DATE_SUB(NOW(), INTERVAL 7 DAY)
我注意到如何获取日期和每日总销售额。我希望得到结果
date daily_sale
2013-01-29 500.00
2013-01-28 500.00
2013-01-27 500.00
2013-01-26 500.00
...
2013-01-23 500.00
答案 0 :(得分:2)
您可以尝试interval - 7 day
:
SELECT date, SUM(Coalese(total,0)) AS daily_sale
FROM yourtable
WHERE date BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL -7 DAY)
不确定为什么between
不起作用,请查看:
<强> SQLFIDDLE DEMO 强>
select dates, sum(coalesce(daily_sale,0)) as total
from sales
where dates <= NOW()
and dates >= Date_add(Now(),interval - 7 day)
group by dates
;
| DATES | TOTAL |
------------------------------------------
| January, 23 2013 00:00:00+0000 | 500 |
| January, 24 2013 00:00:00+0000 | 500 |
| January, 27 2013 00:00:00+0000 | 1500 |
| January, 28 2013 00:00:00+0000 | 1000 |
| January, 29 2013 00:00:00+0000 | 500 |
答案 1 :(得分:0)
来自MySQL BETWEEN...AND manual
expr BETWEEN min AND max
将其改为
SELECT CURDATE( ),DATE_SUB( CURDATE() , INTERVAL 7 DAY ) AS weekEndDate,
`date` , SUM( COALESCE(`daily_sale`,0 ) ) AS weekly_sale
FROM tbl_sale
GROUP BY weekEndDate
LIMIT 0 , 30
注意:
`
SUM(column_name)
,您的列名为 daily_sales 答案 2 :(得分:0)
如果第一个日期表达式需要是较低的一个,正如@ diEcho的回答所示,那么你需要在表达式中使NOW()
成为第二个术语,而不是第一个。
答案 3 :(得分:0)
你应该在BETWEEN命令中使用最低日期,所以NOW()必须在最后
SELECT
date,
IFNULL( SUM( total ), 0 ) AS daily_sale
FROM sales
WHERE date BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) and NOW()
或者如果您每天都需要统计数据:
SELECT
DATE(`date`),
IFNULL( SUM( total ), 0 ) AS daily_sale
FROM sales
WHERE date BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) and NOW()
group by DATE(`date`)