我正在制作股票代码作为PostgreSQL和AngularJS的学习经历。
在我的股票查询中,我试图发现前一天的价格变化。我现在正在用PHP实现数据库查询以便于测试,稍后我将移植到AngularJS。
数据库设置
prices
--pk
--fund (foreign key to funds.pk)
--price
--price_date
funds
--pk
--fund_name
--summary
查询 通过价格表中的条目获取每个基金的最新价格和价格(以及其他信息)。 这个$查询是我的PHP文件中的一行。
$query = 'SELECT prices.price_date,
prices.price,
(lag(prices.price) over (ORDER BY prices.price_date DESC)) as last_price,
prices.fund,
funds.fund_name
FROM prices
INNER JOIN funds ON prices.fund=funds.pk
WHERE price_date=(SELECT price_date FROM prices ORDER BY price_date DESC LIMIT 1)';
结果
[
{"price_date":"2015-09-08","price":"17.5901","last_price":null,"fund":"1","fund_name":"L Income"},
{"price_date":"2015-09-08","price":"22.8859","last_price":"17.5901","fund":"2","fund_name":"L 2020"},
{"price_date":"2015-09-08","price":"24.6693","last_price":"22.8859","fund":"3","fund_name":"L 2030"},
{"price_date":"2015-09-08","price":"26.1456","last_price":"24.6693","fund":"4","fund_name":"L 2040"},
{"price_date":"2015-09-08","price":"14.7756","last_price":"26.1456","fund":"5","fund_name":"L 2050"},
{"price_date":"2015-09-08","price":"14.8181","last_price":"14.7756","fund":"6","fund_name":"G Fund"},
{"price_date":"2015-09-08","price":"16.93","last_price":"14.8181","fund":"7","fund_name":"F Fund"},
{"price_date":"2015-09-08","price":"26.369","last_price":"16.93","fund":"8","fund_name":"C Fund"},
{"price_date":"2015-09-08","price":"35.9595","last_price":"26.369","fund":"9","fund_name":"S Fund"},
{"price_date":"2015-09-08","price":"24.0362","last_price":"35.9595","fund":"10","fund_name":"I Fund"}
]
正如您所看到的,lag()窗口函数仅绘制当前结果集以提取前一个记录的price.price字段。
我现在不知所措。有人有指导吗?
答案 0 :(得分:1)
我猜你想要前一天fund
的价格。这需要partition by
子句:
SELECT p.price_date, p.price,
lag(p.price) over (PARTITION BY p.fund ORDER BY p.price_date DESC) as last_price,
p.fund, p.fund_name
FROM prices p INNER JOIN
funds f
ON p.fund = f.pk ;
如果您只想在最后一个日期使用此选项,请使用子查询:
SELECT pf.*
FROM (SELECT p.price_date, p.price,
lag(p.price) over (PARTITION BY p.fund ORDER BY p.price_date DESC) as last_price,
p.fund, p.fund_name
FROM prices p INNER JOIN
funds f
ON p.fund = f.pk
) pf
WHERE price_date = (SELECT price_date FROM prices ORDER BY price_date DESC LIMIT 1);
在分析函数之前评估WHERE
子句,因此过滤会影响LAG()
选择的记录(如果有)。注意:这假设所有基金的最大price_date
都相同,但这是问题中的逻辑。