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

How to format sql table using values as column

I have the following result :

-------------------------
| dept | Active request |
-------------------------
| AFG  | 3              |
| AGO  | 4              |
| KMN  | 1              |
| MOL  | 1              |
| POD  | 2              |
| SUD  | 2              |
-------------------------

How can I tranform it to have something like

--------------------------------------------------------------
| Title          | AFG | AGO | KMN | MOL | POD | SUD | TOTAL | 
--------------------------------------------------------------
| Active Request | 3   | 4   | 1   | 1   | 2   | 2   | 13    |
--------------------------------------------------------------

Here is my fiddle http://sqlfiddle.com/#!9/b51a03/3

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

>Solution :

You could use a single pivot query:

SELECT
    'Active Request' AS Title,
    COUNT(*) FILTER (WHERE dept = 'AFG') AS AFG,
    COUNT(*) FILTER (WHERE dept = 'AGO') AS AGO,
    COUNT(*) FILTER (WHERE dept = 'KMN') AS KMN,
    COUNT(*) FILTER (WHERE dept = 'MOL') AS MOL,
    COUNT(*) FILTER (WHERE dept = 'POD') AS POD,
    COUNT(*) FILTER (WHERE dept = 'SUD') AS SUD,
    COUNT(*) AS TOTAL
FROM req
WHERE active;
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