Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何计算Postgres中当前行和上一行之间的更改百分比?_Sql_Postgresql_Group By - Fatal编程技术网

Sql 如何计算Postgres中当前行和上一行之间的更改百分比?

Sql 如何计算Postgres中当前行和上一行之间的更改百分比?,sql,postgresql,group-by,Sql,Postgresql,Group By,我有一个名为预订的表,其中包含以下列: 开始时间(时间戳) 插槽(int) 我想按天对预订的时段进行汇总,然后计算与前一天相比的变化% 此查询几乎可以做到这一点,但由于某些原因,百分比不正确: SELECT starttime::date AS "Dates", SUM(slots) AS "Slots", (SUM(Slots)/LAG(SUM(Slots)) OVER (ORDER BY starttime::date))::NUMERIC(3,2)

我有一个名为预订的表,其中包含以下列:

开始时间(时间戳)

插槽(int)

我想按天对预订的时段进行汇总,然后计算与前一天相比的变化%

此查询几乎可以做到这一点,但由于某些原因,百分比不正确:

SELECT starttime::date AS "Dates", SUM(slots) AS "Slots", 
(SUM(Slots)/LAG(SUM(Slots)) OVER (ORDER BY starttime::date))::NUMERIC(3,2) AS "Change (%)"
FROM cd.bookings
GROUP BY 1;
这是输出:

DATES        Slots  Change(%)
"2012-07-03"    10  NULL
"2012-07-04"    22  2.00
"2012-07-05"    19  0.00
"2012-07-06"    23  1.00
"2012-07-07"    42  1.00
"2012-07-08"    36  0.00
"2012-07-09"    43  1.00
我做错了什么?

在除法之前转换为非整数:

SELECT starttime::date AS "Dates", SUM(slots) AS "Slots", 
       (SUM(Slots) * 1.0 /
        LAG(SUM(Slots)) OVER (ORDER BY starttime::date)
        )::NUMERIC(3,2) AS "Change (%)"
FROM cd.bookings
GROUP BY 1;

当两个操作数都是整数时,Postgres进行整数除法,因此0/1是0而不是0.5。

整数除法。将总和转换为类似双精度的数据类型。