0

I have 3 Tables SQL

  • products[id, name_product]
  • customers [id, name_customer]
  • data_prodcuts[id, id_product, id_customer, quantity_data]

How convert in PHP & MYSQL rows table prodcuts name to columns
and get group id_product sum(quantity_data) for all customers rows.

Thanks ..

I'm use SQL

SELECT 
data_prodcuts.id_product, 
sum(data_prodcuts.quantity_data) as total,
data_prodcuts.id_customer,
products.name_product,
customers.name_customer
FROM data_prodcuts
LEFT JOIN products ON products.id = data_prodcuts.id_product
LEFT JOIN customers ON customers.id = data_prodcuts.id_customer
GROUP BY name_product, name_customer

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Amer
  • 1
  • 2
  • 1
    Are you using MySQL or MS SQL Server? The answer wont fit both. – jarlh Nov 24 '17 at 11:15
  • Most people here want formatted text, not images (or links to images.) – jarlh Nov 24 '17 at 11:16
  • I'm use PHP & MySQL – Amer Nov 24 '17 at 11:17
  • search on pivot this question is asked alot.. – Raymond Nijland Nov 24 '17 at 11:28
  • This transformation is called pivoting and has been asked and answered many times here on SO. The linked duplicate topics describe you how to create pivot tables within MySQL. The `MySQL pivot row into dynamic number of columns` also describes how to do the pivoting for unknown number of products. – Shadow Nov 24 '17 at 11:49
  • The End SQL : SELECT id_customer, sum( if( id_product = 1, quantity_data, 0 ) ) AS P1, sum( if( id_product = 2, quantity_data, 0 ) ) AS P2 FROM data_products GROUP BY id_customer; – Amer Nov 24 '17 at 12:34
  • Please don't post the answer in the question. Since your question is a duplicate, your answer probably applies to at least one of the duplicate targets, so post your answer there (as an answer). If you don't think your question is a duplicate, please [edit] to explain why (if that's what you want to do, I suggest you read [this](https://meta.stackexchange.com/a/194479/349538) before doing anything). – Donald Duck Nov 25 '17 at 20:47

0 Answers0