【发布时间】: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