-2

I’m having some trouble while transposing some table rows into columns based on joins using MySQL. I know it’s a database issue, but maybe someone could give me an alternative solution.

Given the following two tables:

INVOICES

enter image description here

COLUMNS

enter image description here

I need to output this table:

enter image description here

Basically, on the first table I save the information of different invoices and the ID of the column where the Total of each invoice should be shown. On the second table I’m saving the different columns I have. The query should be dynamic, so if I create new columns on the second table I wouldn’t have to update my query.

  • Please see [Why should I provide an MCRE for what seems to me to be a very simple SQL query](http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query) – Strawberry Mar 03 '21 at 16:20
  • This is PIVOT, not transpose. But your case is simple - use 3 separate expressions with according CASE. – Akina Mar 03 '21 at 16:24

1 Answers1

0
SELECT id_invoice,
       CASE WHEN description = 'A' THEN total ELSE '' END a,
       CASE WHEN description = 'B' THEN total ELSE '' END b,
       CASE WHEN description = 'C' THEN total ELSE '' END c
FROM invoices
JOIN columns USING (id_column)
Akina
  • 39,301
  • 5
  • 14
  • 25