简体   繁体   English

如何在 SQL 中使用数据透视表

[英]How to use pivot in SQL

SELECT * FROM (SELECT year, amount, month FROM test) AS table1
PIVOT
    (SUM(amount) 
    for month in ('1' as m1, '2' as m2, '3' as m3, '4' as m4)) AS table2
GROUP BY year;

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'sum(amount) for month in ('1' as m1, '2' as m2, '3' as m3, '4' as m4)) as ta' at line 4错误代码: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'sum(amount) for month in ('1' as m1, '2' as m2, '3' as m3, '4' as m4)) as ta' at line 4 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'sum(amount) for month in ('1' as m1, '2' as m2, '3' as m3, '4' as m4)) as ta' at line 4

What causes this error?是什么导致了这个错误?

You can do this with conditional aggregation.您可以使用条件聚合来做到这一点。 This is a portable syntax, that works in most databases:这是一种可移植的语法,适用于大多数数据库:

select
    year,
    sum(case when month = 1 then amount else 0 end) m1,
    sum(case when month = 2 then amount else 0 end) m2,
    sum(case when month = 3 then amount else 0 end) m3,
    sum(case when month = 4 then amount else 0 end) m4
from table1
group by year

MySQL, even version 8 , doesn't support PIVOT Clause, you can prefer using Conditional Aggregation through Dynamic SQL instead, using CONCAT() and GROUP_CONCAT() functions such as MySQL,即使是版本 8也不支持PIVOT Clause,您可以更喜欢通过动态 SQL 使用条件聚合,使用CONCAT()GROUP_CONCAT()函数,例如

SET @sql = NULL;

SELECT GROUP_CONCAT(
             DISTINCT
             CONCAT(
                    'SUM(CASE WHEN month = ', month,' THEN AMOUNT ELSE 0 END) AS m',month
                    )
       )
  INTO @sql
  FROM tab;

SET @sql = CONCAT('SELECT year,',@sql,' FROM tab GROUP BY year'); 

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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