我想在Oracle 11g中旋转一个表。枢纽选项需要汇总。这是我的原始表:
project | attribute | value =========================== 'cust1' | 'foo' | '4' 'cust2' | 'bar' | 'tbd' 'cust3 | 'baz' | '2012-06-07' 'cust1' | 'bar' | 'tdsa' 'cust4' | 'foo' | '22' 'cust4' | 'baz' | '2013-01-01'
旋转后,表格应如下所示:
project | foo | bar | baz ========================= 'cust1' | '4' |'tdba'| NULL 'cust2' | NULL|'tbd' | NULL 'cust3' | NULL| NULL | '2012-06-07' 'cust4' | '22'| NULL | '2013-01-01'
现在,如您所见,分组应该在项目列上进行。无需折叠或计算值。只需旋转即可。那么,枢轴选择正确的事情了吗?
是的,我想是这样。使用MAX汇总很容易进行这样的枢轴操作:
MAX
SELECT * FROM ( SELECT project, attribute, value FROM table1 ) AS SourceTable PIVOT ( MAX(value) FOR attribute IN ([foo],[bar],[baz]) ) AS pvt
否则,您必须在max聚合内执行case语句。像这样:
SELECT MAX(CASE WHEN attribute='foo' THEN value ELSE NULL END) AS foo, MAX(CASE WHEN attribute='bar' THEN value ELSE NULL END) AS bar, MAX(CASE WHEN attribute='baz' THEN value ELSE NULL END) AS baz, project FROM table1 GROUP BY project
这几乎和做PIVOT。但我宁愿做PIVOT在CASE WHEN MAX..
PIVOT
CASE WHEN MAX