我一直试图想出一个以特定方式显示数据的查询,而我一直在努力。
假设有这些数据
ID Amount Date
1 10 10/10/2014 13:45
1 20 10/10/2014 14:56
1 05 10/10/2014 22:45
1 10 11/10/2014 23:04
1 30 14/10/2014 03:00
1 15 14/10/2014 04:34
1 15 15/10/2014 13:34
2 10 10/10/2014 16:05
我想使用开始日期和结束日期调用查询,并使用每日行显示结果,该行包含该ID的当天金额总和。 结果将是:
对于Id = 1,StartDate = 10/10 / 2014和EndDate = 2014年10月14日:
Date Sum
10/10/2014 35
11/10/2014 10
12/10/2014 0
13/10/2014 0
14/10/2014 45
现在我已经尝试过的东西了,我在jFiddle中创建了一个脚本:
CREATE TABLE TableName
(`id` int, `amount` int, `timestamp` datetime)
;
INSERT INTO TableName
(`id`, `amount`, `timestamp`)
VALUES
(1, 10, '2013-01-06 12:23:56'),
(1, 15, '2013-01-06 02:23:41'),
(1, 15, '2013-01-07 14:23:42'),
(1, 0, '2013-01-08 04:23:56'),
(1, 5, '2013-01-08 16:23:25'),
(1, 20, '2013-01-08 12:23:57'),
(1, 10, '2013-01-08 23:23:40'),
(1, 0, '2013-01-09 07:23:56'),
(1, 5, '2013-01-12 17:23:25'),
(1, 20, '2013-01-13 22:23:57'),
(1, 10, '2013-01-14 09:23:40'),
(1, 10, '2013-01-14 19:23:23'),
(1, 35, '2013-01-15 15:23:55'),
(1, 40, '2013-01-15 21:29:38'),
(2, 40, '2013-01-06 02:31:59');
我使用各种方法将它用作游乐场,我在互联网上找到了运气不多。
知道如何在该结构中获取数据吗?
答案 0 :(得分:3)
您需要生成所有日期。这很痛苦,但以下适用于您的数据:
select d.dte, coalesce(sum(tn.amount), 0)
from ((select date(timestamp) as dte from tablename) union
(select date(timestamp) + interval 1 day from tablename) union
(select date(timestamp) - interval 1 day from tablename)
) d left outer join
tablename tn
on date(tn.timestamp) = d.dte
group by d.dte
order by 1;
编辑:
如果要将这些限制为表格中的日期,请添加:
where d.dte between (select min(date(timestamp) from tablename) and
(select max(date(timestamp) from tablename)
如果差距较大,请在selects
子查询中添加更多d
,或使用日历表(后者更容易)。
Here是SQL小提琴。
答案 1 :(得分:1)
select
date(timestamp) as my_date,
sum(amount)
from TableName
where id = 1
and timestamp between <start_date> and <end_date>
group by my_date
如果您正在传递时间戳,请between
再次使用date()
功能。