【问题标题】:How to use pivot in SQL如何在 SQL 中使用数据透视表
【发布时间】:2020-12-24 09:46:59
【问题描述】:
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;

错误代码: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

是什么导致了这个错误?

【问题讨论】:

  • 样本数据和预期结果会有所帮助。请使用 {} 格式化您的代码。
  • MySQL 好像不支持pivot。您可以查看 stackoverflow.com/questions/7674786/… 。您需要使用案例和聚合来实现相同的效果。
  • 我建议您在 SQL 中使用大写字母,以帮助阅读您的代码。我建议对其进行修改。

标签: mysql sql pivot


【解决方案1】:

您可以使用条件聚合来做到这一点。这是一种可移植的语法,适用于大多数数据库:

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

【讨论】:

    【解决方案2】:

    MySQL,甚至版本 8,不支持 PIVOT 子句,您可以更喜欢通过动态 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

    【讨论】:

      猜你喜欢
      • 2021-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-05
      • 2012-07-21
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多