我在使用crosstab()
函数在PostgreSQL中创建数据透视表时遇到问题。它运行良好,但它为同一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);
//修改
对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;
答案 0 :(得分:3)
您需要ORDER BY
相应的第一个查询。我在这里使用了simplified syntax 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中,但附带additional module 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;