由于先前的查询,我具有下brands表中的total每销售量month:
brands
total
month
id | date | total -----+----------+------ 123 | Apr-2012 | 100 123 | Mar-2012 | 150 123 | Jan-2012 | 500 987 | Apr-2012 | 5 987 | Mar-2012 | 0.10 987 | Feb-2012 | 8
我希望实现以下目标:
id | Apr-2012 | Mar-2012 | Feb-2012 | Jan-2012 123 | 100 | 150 | 0 | 500 987 | 5 | 0.10 | 8 | 0
如何将这些date值用作列,并能够用总计0填写缺失的日期?
date
一个crosstab()为你的榜样查询应该是这样的:
crosstab()
要填写0结果NULL值(在注释中请求),请使用COALESCE():
0
NULL
COALESCE()
SELECT brand_id , COALESCE(jan, 0) AS "Jan-2012" , COALESCE(feb, 0) AS "Feb-2012" , COALESCE(mar, 0) AS "Mar-2012" , COALESCE(apr, 0) AS "Apr-2012" FROM crosstab( 'SELECT brand_id, month, total FROM brands ORDER BY 1' ,$$VALUES ('Jan-2012'::text), ('Feb-2012'), ('Mar-2012'), ('Apr-2012')$$ ) AS ct ( brand_id int , jan numeric -- use actual data type! , feb numeric , mar numeric , apr numeric);
除了:不使用保留字“ date”作为列名,即使Postgres允许也不使用它。