给定此表:
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]
的值作为COPPER
的NULL
?
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}"
SQL Fiddle
select
commodity,
array_agg(
case when commodity = 'COPPER' then null else price end
order by date desc
)
from CommodityPricing
group by commodity
;
To "pad"如果在结果数组中缺少具有空值的行,则在完整的行和 LEFT JOIN
上构建查询,以获取网格的实际值。
给定这个表定义:
CREATE TABLE price (
commodity text
, value numeric
, ts timestamp -- using ts instead of the inappropriate name date
);
使用generate_series()
获取代表年份的时间戳列表,使用CROSS JOIN
获取所有商品的唯一列表(SELECT DISTINCT ...
)。
SELECT commodity, array_agg(value ORDER BY ts DESC) AS years
FROM generate_series (timestamp '2002-01-01'
, timestamp '2004-01-01'
, '1 year') t(ts)
CROSS JOIN (SELECT DISTINCT commodity FROM price) c(commodity)
LEFT JOIN price p USING (ts, commodity)
GROUP BY commodity;
结果:<表类> 商品 tbody> <<tr>铜> 空,99.45,96.45}金道明> {150.45,140.45,130.45} {60,零,零} 银 {80.45,70.45,60.45} tbody> 表类>