我在使用该crosstab()函数在PostgreSQL中创建数据透视表时遇到问题。它运作良好,但可以产生多个记录client_id。如何避免这种情况?
crosstab()
client_id
这是SQL:
SELECT * FROM crosstab('SELECT client_id ,extract(year from date) ,sum(amount) from orders group by extract(year from date) ,client_id' ,'SELECT extract(year from date) FROM orders GROUP BY extract(year from date) order by extract(year from date)') AS orders( row_name integer, year_2001 text, year_2002 text, year_2003 text, year_2004 text, year_2005 text, year_2006 text, year_2007 text, year_2008 text, year_2009 text, year_2010 text, year_2011 text);
//编辑
Thx to Erwin现在可以使用了,但是我试图在没有内置函数的情况下做到这一点,但是没有运气。有人可以提出建议吗?我的代码只有两年了:
SELECT DISTINCT o.client_id, CASE WHEN (extract(year from o.date)=2001) THEN sum(o.amount) ELSE 0 END, CASE WHEN (extract(year from o.date)=2002) THEN sum(o.amount) ELSE 0 END FROM orders AS o GROUP BY 1, extract(year from o.date) ORDER BY 1;
您需要相应地ORDER BY进行第一个查询。我在这里使用简化的语法 ORDER BY <ordinal number>。
ORDER BY
ORDER BY <ordinal number>
SELECT * FROM crosstab( 'SELECT client_id ,extract(year from date) ,sum(amount) FROM orders GROUP BY 1,2 ORDER BY 1,2', 'SELECT extract(year from date) FROM orders GROUP BY 1 ORDER BY 1') AS orders( row_name integer, year_2001 text, year_2002 text, year_2003 text, year_2004 text, year_2005 text, year_2006 text, year_2007 text, year_2008 text, year_2009 text, year_2010 text, year_2011 text);
该crosstab()函数未包含在标准PostgreSQL中,但附带了附加的模块tablefunc。
没有crosstab()功能的版本:仅按分组,client_id否则每个会导致多行client_id。
SELECT client_id ,sum(CASE WHEN extract(year from date) = 2001 THEN amount ELSE 0 END) AS year_2001 ,sum(CASE WHEN extract(year from date) = 2002 THEN amount ELSE 0 END) AS year_2002 -- ... FROM orders o GROUP BY 1 ORDER BY 1;