【问题标题】:Dynamic Pivot CASE WHEN got error #1064 - You have an error in your SQL syntax;Dynamic Pivot CASE WHEN 出现错误 #1064 - 你的 SQL 语法有错误;
【发布时间】:2023-02-23 16:32:05
【问题描述】:
SET @sql = NULL;
set @sql = (
                select group_concat(distinct
                concat(
                "(CASE WHEN param_code IN ('20', '43')
                THEN EXP(AVG(CASE WHEN YEAR(`res_date`) = '", YEAR(`res_date`),"'  THEN LOG(`res_value`) END))
                ELSE AVG(CASE WHEN YEAR(`res_date`) =  '", YEAR(`res_date`),"'  THEN `res_value` END)
                END) as  '",YEAR(`res_date`),"'"
                )   
                )
                from wq_results
                );
                
set @sql = concat("select station_id AS ID, tbl2.station_name, param_code, ", @sql, " from wq_results as tbl1 left join mon_stations as tbl2 on tbl1.station_id = tbl2.id  where sc_id='20' and param_code = IN (20,43) group by station_id");
prepare stmt from @sql;
execute stmt;

tbl1 wq_results

id station_id param_code res_value res_date
1 1 20 1,452 2021-12-06
2 1 20 85 2022-12-06
3 1 20 1,854 2023-01-06
4 1 43 67 2023-01-06
5 2 43 1,285 2023-12-06

tbl2 mon_stations

id station_name
1 Station 1
2 Station 2

输出应该是这样的

Station ID Station Name Parameter 2021 2022 2023
1 Station 1 20 1,452 85 8,254
2 Station 2 43 - - 1,285
1 Station 1 43 - - 67

【问题讨论】:

  • 其中 sc_id='20' 和 param_code = IN (20,43) - remove = voting to close as typo 另外 sc_id 从哪里来?

标签: mysql


【解决方案1】:

尝试这个 :

你有一个与group by相关的错误,你应该包括tbl1.station_id, tbl2.station_name, param_code

可以删除 where 子句

SET @sql = NULL;
set @sql = (
            select group_concat(
                  distinct concat(
                "(CASE WHEN param_code IN ('20', '43') THEN EXP(AVG(CASE WHEN YEAR(`res_date`) = '", YEAR(`res_date`),"'  THEN LOG(`res_value`) END)) ELSE AVG(CASE WHEN YEAR(`res_date`) =  '", YEAR(`res_date`),"'  THEN `res_value` END) END) 
                 as  '",YEAR(`res_date`), "'"
                  )   
            )
            from wq_results
          );
                
set @sql = concat("select tbl1.station_id AS ID, tbl2.station_name, param_code, ", @sql, " 
                 from wq_results as tbl1 
                 left join mon_stations as tbl2 on tbl1.station_id = tbl2.id  
                 where param_code IN (20,43) 
                 group by tbl1.station_id, tbl2.station_name, param_code");
select @sql;
prepare stmt from @sql;
execute stmt;

Demo here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多