如何在oracle中根据日期总结数据库字段值

时间:2018-01-17 10:41:06

标签: sql database oracle

我有一张桌子,里面有两个字段,如下图所示。

enter image description here

如何创建一个视图,该视图将TOT_HITS字段的值相加,直到每个日期出现在TODAY列的相应行中,如下所示。

enter image description here

2 个答案:

答案 0 :(得分:3)

使用分析函数仅使用一次表扫描执行查询:

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE your_table( today, tot_hits ) As
SELECT DATE '2018-01-16', 5498 FROM DUAL UNION ALL
SELECT DATE '2018-01-17', 4235 FROM DUAL;

查询1

SELECT t.*,
       SUM( tot_hits ) OVER ( ORDER BY today ) AS tot_hits_to_date
FROM   your_table t

<强> Results

|                TODAY | TOT_HITS | TOT_HITS_TO_DATE |
|----------------------|----------|------------------|
| 2018-01-16T00:00:00Z |     5498 |             5498 |
| 2018-01-17T00:00:00Z |     4235 |             9733 |

答案 1 :(得分:1)

试试这个

SELECT
    Today,
    Hits,
    TillDate = Hits+NVL((SELECT SUM(Hits) FROM YourTable  WHERE Today < T.Today),0)
    FROM YourTable T