如何在表格中的数据以秒为单位显示每日的历史数据?

时间:2017-10-06 00:24:47

标签: sql oracle

您好我有一张时间戳精度高达秒的表(表A),业务要求是以日,周,月和年为基础显示历史数据。 Database = Oracle和后端应用程序是Java spring boot。

表:

╔════╤══════╤═════════════════════╗
║ id │ data │ created             ║
╠════╪══════╪═════════════════════╣
║ 1  │ 40   │ 2017-10-06 10:00:00 ║
╟────┼──────┼─────────────────────╢
║ 2  │ 30   │ 2017-10-06 23:59:59 ║
╟────┼──────┼─────────────────────╢
║ 3  │ 1000 │ 2017-10-07 12:00:00 ║
╚════╧══════╧═════════════════════╝

预期输出样本:

╔══════╤════════════╗
║ data │ created    ║
╠══════╪════════════╣
║ 70   │ 2017-10-06 ║
╟──────┼────────────╢
║ 1000 │ 2017-10-07 ║
╚══════╧════════════╝

我可以在这里看到两个选项:

  1. 创建一些其他表(表B)或存储过程,通过对表A进行求和并仅查询表B /存储过程来自动累积数据。

  2. 使用正确的SQL直接从表A后端应用查询数据。

  3. 有人可以建议是否有更多选择,哪个最好?

1 个答案:

答案 0 :(得分:1)

这是一个简单的group by。要摆脱时间戳的时间部分,您可以使用trunc()to_char()

select sum(data) as data,
       trunc(created) as day_created
from the_table
group by trunc(created);

select sum(data) as data,
       to_char(created, 'yyyy-mm-dd') as day_created
from the_table
group by to_char(created, 'yyyy-mm-dd');
在处理其他级别的聚合时,

to_char()更灵活,例如获得每月的数字:

select sum(data) as data,
       to_char(created, 'yyyy-mm') as month_created
from the_table
group by to_char(created, 'yyyy-mm');