Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
984 views
in Technique[技术] by (71.8m points)

sql - Convert Row to Column

How can I convert this table:-

INV   DESCRIPTION   AMOUNT
--------------------------
1001  CHARGES       100
1001  FREIGHT       30
1001  INSURANCE     20
1002  CHARGES       215
1002  FREIGHT       32
1002  INSURANCE     25

to this format using SQL:-

INV   CHARGES  FREIGHT  INSURANCE
---------------------------------
1001  100      30       20
1002  215      32       25
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use:

  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

In order to support a dynamic list of descriptions, you'd have to specify which database this is for because the dynamic SQL syntax is different for each one.

PIVOT/UNPIVOT is ANSI syntax, but support is limited:

  • SQL Server 2005+
  • Oracle 11g+

MySQL doesn't support PIVOT, nor does SQLite. I don't know when/if PostgreSQL or DB2 does...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...