我的环境是postgresql 9.5 +
如果可能,我想用窗口函数计算成本平均值
例如
kdproduk code tgl qty harga totalharga
abc 2 2016-10-20 5 10000 50000
abc 4 2016-10-21 -3 12000 36000
abc 2 2016-10-22 10 13000 130000
然后我的查询是:
with ab as (
SELECT
kdproduk,
code,
tgl,
qty,
harga,
totalharga,
coalesce(hargarata2, 0) as hargarata2,
sum(qty) OVER (PARTITION BY kdproduk ORDER BY kdproduk, tgl, code) AS running_qty
FROM ms_kartustok
ORDER BY kdproduk, tgl, code )
select kdproduk, code, tgl, qty, harga, totalharga, coalesce(running_qty, 0) + qty as running_qty, case
when code = 2 then (totalharga + coalesce(hargarata2, 0)) / (coalesce(running_qty, 0) + qty)
else hargarata2 end as rata2 from (
SELECT
kdproduk,
code,
tgl,
qty,
harga,
totalharga,
lag(hargarata2) OVER (PARTITION BY kdproduk ORDER BY kdproduk, tgl, code) AS hargarata2,
lag(running_qty) OVER (PARTITION BY kdproduk ORDER BY kdproduk, tgl, code) AS running_qty
FROM ab
ORDER BY kdproduk, tgl, code ) as a
我的查询结果是:
kdproduk code tgl qty harga totalharga running_qty rata2
abc 2 2016-10-20 5 10000 50000 5 10000
abc 4 2016-10-21 -3 12000 36000 2 0
abc 2 2016-10-22 10 13000 130000 12 10833.333333333334
但我希望结果是:
kdproduk code tgl qty harga totalharga running_qty rata2
abc 2 2016-10-20 5 10000 50000 5 10000
abc 4 2016-10-21 -3 12000 36000 #2# #10000#
abc 2 2016-10-22 10 13000 #130000# 12 12500
如果"代码"是4,然后是我的专栏" rata2"是以前" rata2"值。 如果"代码"是2,那么我的专栏" rata2"价值是: (totalharga +"&#34之前的rata2值;)/(qty +"&#34之前的running_qty值;)
第3行是:
(130000 + (2*10000)) / (10 + 2) = 12500
编辑: 看到上面的表格,我使用符号#
如何解决这个问题?
感谢。