简体   繁体   中英

Transposing mysql query

I've seen many answers for questions like this, but none of the queries are explained, thus I can't understand it and use for my case.

SELECT st.name, SUM(sa.val), sa.sale_date FROM sales sa
INNER JOIN employee e ON sa.employee_id
INNER JOIN store st ON e.store_id
GROUP BY st.name, sa.sale_date

Considering the following query result:

http://sqlfiddle.com/#!9/0faa35/5

+---------+-------------+------------------------+
|  name   | SUM(sa.val) |       sale_date        |
+---------+-------------+------------------------+
| Store 1 |         800 | July, 29 2015 00:00:00 |
| Store 1 |         700 | July, 30 2015 00:00:00 |
| Store 2 |         800 | July, 29 2015 00:00:00 |
| Store 2 |         700 | July, 30 2015 00:00:00 |
+---------+-------------+------------------------+

I need to transpose(Grouping the store name) it so it becomes:

+------------+---------+---------+
|    Date    | Store 1 | Store 2 |
+------------+---------+---------+
| 2015-07-29 |     800 |     800 |
| 2015-07-30 |     700 |     700 |
+------------+---------+---------+

This is a basic pivot query. In MySQL, the easiest way is conditional aggregation. Given the query in your SQL Fiddle, the logic is:

SELECT sa.sale_date,
       SUM(CASE WHEN st.name = 'Store 1' THEN val ELSE 0 END) as Store1,
       SUM(CASE WHEN st.name = 'Store 2' THEN val ELSE 0 END) as Store2
FROM sales sa INNER JOIN
     employee e
     ON sa.employee_id INNER JOIN
     store st
     ON e.store_id
GROUP BY sa.sale_date;

Note: you should put the actual query in your question.

Here is a SQL Fiddle.

You can use a prepared query :

SELECT CONCAT(
  'SELECT sales.sale_date,',
  GROUP_CONCAT('SUM(
     CASE WHEN employee.store_id = ', id , '
     THEN val
     ELSE 0 END) AS `', REPLACE(name, ' ', ''), '`' SEPARATOR ','),
' FROM
  employee
  INNER JOIN sales ON(employee.id = employee_id)
  GROUP BY sales.sale_date'
) INTO @qry FROM (SELECT name,id FROM store) as stores;
PREPARE stmt FROM @qry;
EXECUTE stmt;

Fiddle: http://sqlfiddle.com/#!9/0faa35/39/2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM