我怎么能转换这个表: –
INV DESCRIPTION AMOUNT -------------------------- 1001 CHARGES 100 1001 FREIGHT 30 1001 INSURANCE 20 1002 CHARGES 215 1002 FREIGHT 32 1002 INSURANCE 25
使用sql格式: –
INV CHARGES FREIGHT INSURANCE --------------------------------- 1001 100 30 20 1002 215 32 25
解决方法
使用:
SELECT t.inv,MAX(CASE WHEN t.description = 'CHARGES' THEN t.amount ELSE NULL END) AS charges,MAX(CASE WHEN t.description = 'FREIGHT' THEN t.amount ELSE NULL END) AS freight,MAX(CASE WHEN t.description = 'INSURANCE' THEN t.amount ELSE NULL END) AS insurance FROM YOUR_TABLE t GROUP BY t.inv ORDER BY t.inv
为了支持动态的描述列表,您必须指定它所针对的数据库,因为每个数据库的动态sql语法都不同.
PIVOT / UNPIVOT是ANSI语法,但支持有限:
> sql Server 2005
> Oracle 11g