Pivoting in DB2

The currently accepted answer by bhamby is certainly correct, but it’s worth checking if using several correlated subqueries is much slower than a single group by (hint: it most likely is): SELECT A.ItemID, MAX(CASE WHEN A.Item = ‘Meeting’ THEN Value END) AS Meeting, MAX(CASE WHEN A.Item = ‘Advise’ THEN Value END) AS Advise, MAX(CASE WHEN … Read more

How to convert Rows to Columns in Oracle? [duplicate]

If you are using Oracle 10g, you can use the DECODE function to pivot the rows into columns: CREATE TABLE doc_tab ( loan_number VARCHAR2(20), document_type VARCHAR2(20), document_id VARCHAR2(20) ); INSERT INTO doc_tab VALUES(‘992452533663’, ‘Voters ID’, ‘XPD0355636’); INSERT INTO doc_tab VALUES(‘992452533663’, ‘Pan card’, ‘CHXPS5522D’); INSERT INTO doc_tab VALUES(‘992452533663’, ‘Drivers licence’, ‘DL-0420110141769’); COMMIT; SELECT loan_number, MAX(DECODE(document_type, ‘Voters … Read more

Oracle Dynamic Pivoting

Using dynamic sql for a result where the columns are unknown at the time of executing is a bit of a hassle in Oracle compared to certain other RDMBS. Because the record type for the output is yet unknown, it can’t be defined beforehand. In Oracle 11g, one way is to use a nameless procedure … Read more

SQL Rows to Columns

You cannot do it with SQL (except with dynamic queries), unless you know the number of columns (i. e. questions) in design time. You should pull the data you want in tabular format and then process it on client side: SELECT * FROM Question LEFT OUTER JOIN Response ON Response.QuestionId = Question.QuestionID or, probably, this … Read more