Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

DB2/AS400 SQL Pivot

I have a problem with pivot tables ….
I don’t understand what to do …
My table is as follows:

|CODART|MONTH|QT  |
|------|-----|----|
|ART1  |1    |100 |
|ART2  |1    |30  |
|ART3  |1    |30  |
|ART1  |2    |10  |
|ART4  |2    |40  |
|ART3  |4    |50  |
|ART5  |4    |60  |

I would like to get a summary table by month:

|CODART|1  |2  |3  |4  |5  |6  |7  |8  |9  |10 |11 |12 |
|------|---|---|---|---|---|---|---|---|---|---|---|---|
|ART1  |100|10 |   |   |   |   |   |   |   |   |   |   |
|ART2  |30 |   |   |   |   |   |   |   |   |   |   |   |
|ART3  |30 |   |   |50 |   |   |   |   |   |   |   |   | 
|ART4  |   |2  |   |   |   |   |   |   |   |   |   |   |
|ART5  |   |   |   |60 |   |   |   |   |   |   |   |   |
|TOTAL |160|12 |   |110|   |   |   |   |   |   |   |   |

Too many requests? 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks for the support

>Solution :

WITH MYTAB (CODART, MONTH, QT) AS 
(
VALUES 
  ('ART1', 1, 100)
, ('ART2', 1,  30)
, ('ART3', 1,  30)
, ('ART1', 2,  10)
, ('ART4', 2,  40)
, ('ART3', 4,  50)
, ('ART5', 4,  60)
)
SELECT 
  CASE GROUPING (CODART) WHEN 0 THEN CODART ELSE 'TOTAL' END AS CODART
, SUM (CASE MONTH WHEN  1 THEN QT END) AS "1"
, SUM (CASE MONTH WHEN  2 THEN QT END) AS "2"
, SUM (CASE MONTH WHEN  3 THEN QT END) AS "3"
, SUM (CASE MONTH WHEN  4 THEN QT END) AS "4"
---
, SUM (CASE MONTH WHEN 12 THEN QT END) AS "12"
FROM MYTAB T
GROUP BY ROLLUP (T.CODART)
ORDER BY GROUPING (T.CODART), T.CODART
CODART 1 2 3 4 12
ART1 100 10
ART2 30
ART3 30 50
ART4 40
ART5 60
TOTAL 160 50 110
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading