我想检索/计算不同资产在给定日期的价格,具体取决于交易的一方。在2000年之前,我有中间报价,之后我出价并询问或提供报价,所以我希望价格是这两个报价的平均值。更确切地说:
SELECT date, price,
CASE WHEN side='' THEN 'price_mid'
WHEN side='A' THEN 'price_ask'
WHEN side='B' THEN 'price_bid'
WHEN side='O' THEN 'price_offer'
END as prices
FROM table
WHERE asset = 'a';
如何在新列中计算价格,具有price_mid(在2000之前)和(price_bid + price_ask)/ 2或(price_bid + price_offer)/ 2之后?
例如:假设我有以下情况:
date price prices
1 1 price_mid
2 1.1 price_mid
3 0.9 price_bid
3 1.2 price_ask
4 1.3 price_offer
4 1.1 price_bid
我想:
date final_price
1 1
2 1.1
3 1.05
4 1.2
答案 0 :(得分:3)
我知道你只需要一些日期的平均值。也许以下是你想要的:
SELECT date, AVG(price) as AvgValue
FROM prices
WHERE date >= 2
AND prices in ('price_ask','price_offer','price_bid')
GROUP BY date
UNION
SELECT date, price as AvgValue
FROM prices
WHERE date < 2
AND prices = 'price_mid'
GROUP BY date
UNION
SELECT date, price as AvgValue
FROM prices p
WHERE date >= 2
AND prices = 'price_mid'
AND NOT EXISTS (SELECT 1 FROM prices p2 where p2.date = p.date AND p2.prices in ('price_ask','price_offer','price_bid'))
GROUP BY date
ORDER BY DATE ASC
答案 1 :(得分:0)
像这样的东西
SELECT `date`, AVG(price) AS final_price FROM tbl GROUP BY 1
答案 2 :(得分:0)
尝试了一些事情,它没有用,但也许这有帮助..
这是您已经拥有的查询的更改版本,但它不保存某种状态,它只在正确的位置上显示所有值。
SELECT
date,
CASE WHEN side = '' THEN price
ELSE NULL
END as price_mid,
CASE WHEN side = 'A' THEN price
ELSE NULL
END as price_ask,
CASE WHEN side = 'B' THEN price
ELSE NULL
END as price_bid,
CASE WHEN side = '' THEN price
ELSE NULL
END as price_offer
FROM
table
WHERE
asset = 'a';
应该给你什么:
date price_mid price_ask price_bid price_offer
1 1 NULL NULL NULL
2 1.1 NULL NULL NULL
3 NULL NULL 0.9 NULL
3 NULL 1.2 NULL NULL
4 NULL NULL NULL 1,4
4 NULL NULL 1.1 NULL
现在,您可以在该表中查看IS NULL
或每个日期SUM()
或MAX()
,这样您就可以在一行中切换案例。