[英]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 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.
在MySQL中,最简单的方法是条件聚合。 Given the query in your SQL Fiddle, the logic is:
给定SQL Fiddle中的查询,逻辑是:
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. 注意:您应该在问题中添加实际查询。
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 小提琴: http ://sqlfiddle.com/#!9/0faa35/39/2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.