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

SQL query to show grouped rows in columns

Query:

SELECT ProductId,LanguageId,FileType 
FROM dbo.ProductFile
GROUP BY ProductId,FileType,LanguageId

Result:

===============================
| Code | Language | File Type |
-------------------------------
| 2040 | English  | manual    |
| 2040 | English  | exploded  |
| 2040 | English  | catalog   |
| 2040 | Dutch    | catalog   |
| 2041 | English  | manual    |
| 2041 | English  | exploded  |
| 2041 | Dutch    | catalog   |
| 2041 | Dutch    | manual    |
===============================

Target: Show each product in each language in a row with each file type in a column

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

=================================================
| Code | Language | manual | exploded | catalog |
-------------------------------------------------
| 2040 | English  | true   | true     | true    |
| 2040 | Dutch    | false  | false    | true    |
| 2041 | English  | true   | true     | false   |
| 2041 | Dutch    | true   | false    | true    |
=================================================

Anyone has experienced please?

>Solution :

You may use conditional aggregation as the following:

SELECT Code, Language,
       MAX(CASE FileType WHEN 'manual' THEN 'true' ELSE 'false' END) manual,
       MAX(CASE FileType WHEN 'exploded' THEN 'true' ELSE 'false' END) exploded,
       MAX(CASE FileType WHEN 'catalog' THEN 'true' ELSE 'false' END) catalog
FROM ProductFile
GROUP BY Code, Language
ORDER BY Code, Language

See a demo.

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