我正在嘗試生成下面的 Table2 - 它基本上計算了同一天的行,并將同一天的行的“金額”列相加。

我在網上找到了一個解決方案,可以計算當天的條目,它有效:
SELECT
DATE_TRUNC('day', datetime) AS date,
COUNT(datetime) AS date1
FROM Table1
GROUP BY DATE_TRUNC('day', datetime);

這部分是我正在尋找的,但我在嘗試顯示所有列名時遇到了困難。
在我的嘗試中,我擁有了我想要的所有列,但累積計數不準確,因為它計算具有唯一 ID 的行(因為我在 GROUP BY 中輸入了“id”):
SELECT *, count(id) OVER(ORDER BY DateTime) as accumulated_count,
SUM(Amount) OVER(ORDER BY DateTime) AS Accumulated_Amount
FROM Table1
GROUP BY date(datetime), id

我已經為此作業了好幾天,似乎遇到了所有可能的結果,這不是我想要的。有人知道我在這里缺少什么嗎?
uj5u.com熱心網友回復:
應計算每天的累計和計數
with Table1 (id,datetime,client,product,amount) as(values
(1 ,to_timestamp('2020-07-08 07:30:10','YYYY-MM-DD HH24:MI:SS'),'Tom','Bill Payment',24),
(2 ,to_timestamp('2020-07-08 07:50:30','YYYY-MM-DD HH24:MI:SS'),'Tom','Bill Payment',27),
(3 ,to_timestamp('2020-07-09 08:20:10','YYYY-MM-DD HH24:MI:SS'),'Tom','Bill Payment',37)
)
SELECT
Table1.*,
count(*) over (partition by DATE_TRUNC('day', datetime)
order by datetime asc ) accumulated_count,
sum(amount) over (partition by DATE_TRUNC('day', datetime) order by datetime asc) accumulated_sum
FROM Table1;
uj5u.com熱心網友回復:
不熟悉postgresql,但這可以滿足您的要求。
with data (id,date_time,client,product,amount) as(
select 1 ,to_timestamp('Jul 08 2020, 07:30:10','Mon DD YYYY, HH24:MI:SS'),'Tom','Bill',24 Union all
select 2 ,to_timestamp('Jul 08 2020, 07:50:30','Mon DD YYYY, HH24:MI:SS'),'Tom','Bill',27 Union all
select 3 ,to_timestamp('Jul 09 2020, 08:20:10','Mon DD YYYY, HH24:MI:SS'),'Tom','Bill',37
)
select d.id,d.date_time,d.client,d.product,d.amount,
(select count(*) from data d1
where d1.date_time <= d.date_time and date(d1.date_time) = date(d.date_time) ) acc_count,
(select sum(amount) from data d1
where d1.date_time <= d.date_time and date(d1.date_time) = date(d.date_time) ) acc_amount
from data d

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/497102.html
標籤:sql PostgreSQL
下一篇:PHP-SQL陳述句創建錯誤
