给定此表:
SELECT * FROM CommodityPricing order by dateField
"SILVER";60.45;"2002-01-01"
"GOLD";130.45;"2002-01-01"
"COPPER";96.45;"2002-01-01"
"SILVER";70.45;"2003-01-01"
"GOLD";140.45;"2003-01-01"
"COPPER";99.45;"2003-01-01"
"GOLD";150.45;"2004-01-01"
"MERCURY";60;"2004-01-01"
"SILVER";80.45;"2004-01-01"
2004年,铜被淘汰,汞被引入。
如何将(array_agg(value order by date desc) ) [1]
的值作为NULL
的COPPER
?
select commodity,(array_agg(value order by date desc) ) --[1]
from CommodityPricing
group by commodity
"COPPER";"{99.45,96.45}"
"GOLD";"{150.45,140.45,130.45}"
"MERCURY";"{60}"
"SILVER";"{80.45,70.45,60.45}"
2条答案
按热度按时间xienkqul1#
SQL Fiddle
wpx232ag2#
要在结果数组中用空值“填充”缺失的行,请在完整的行网格和**
LEFT JOIN
**上构建查询,以将实际值添加到网格中。给定此表定义:
使用
generate_series()
获取表示年份的时间戳列表,使用CROSS JOIN
获取所有商品的唯一列表(SELECT DISTINCT ...
)。结果:
| 年| years |
| - -----| ------------ |
| {NULL,99.45,96.45}| {NULL,99.45,96.45} |
| 【2019 - 04 - 25】| {150.45,140.45,130.45} |
| {60,NULL,NULL}| {60,NULL,NULL} |
| [2019 - 04 - 25]| {80.45,70.45,60.45} |
fiddle
老麻雀
相关内容: