I would like to know if there would be a way to improve a code I made on hand in SQL ... I have a table of the following Table
Chave identificadora - DataProduto - Preço - Marca
Lanche - Pao/presunto - 01/01/2017 - 5.90 - McDonalds
Lanche - Pao/presunto - 01/01/2017 - 5.90 - McDonalds
Lanche - Pao/presunto - 01/02/2017 - 5.90 - McDonalds
Jantar- Pao/presunto - 01/01/2017 - 5.90 - Burger King
Almoço- Pao/presunto - 01/01/2017 - 5.90 - KFC
Being the first line of my header I need to group this and turn the tags into columns so I did the following way:
SELECT [Chave identificadora], DataProduto,SUM(McDonalds)McDonalds, SUM(BurgerKing)BurgerKing,SUM(KFC)[KFC]
FROM (
SELECT DISTINCT [Chave identificadora], DataProduto,
CASE WHEN MARCA = 'McDonalds' THEN Preço ELSE 0 END as McDonalds,
CASE WHEN MARCA = 'Burger King' THEN Preço ELSE 0 END as BurgerKing,
CASE WHEN MARCA = 'KFC' THEN Preço ELSE 0 END as KFC
from Tabela_Produtos
) AS A
group by chaveidentificadora,dataproduto
Order by dataproduto
This will return me exactly
Chave - Data - McDonalds - BurgerKing - KFC
Lanche - 01/01/2017 - 11.80 - 5.90 - 5.90
Lanche - 01/02/2017 - 5.90 - 0.00 - 0.00
That is, that's correct! but in this case I wrote 3 marks (bk, kfc and mc) if I had 500 marks I would have to write in hand. My doubt would be, would I have a way to improve this by making it dependent on 1.5.10 thousand records I run a certain code / procedure that will leave it ready? (I apologize if I have not been clear enough)