By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
create table TEST_TABLE (
DT date,
OBJECT_ID NUMERIC,
PARAM_VALUE NUMERIC
);
insert TEST_TABLE (DT, OBJECT_ID, PARAM_VALUE) values ('2022-01-01',1, 21);
insert TEST_TABLE (DT, OBJECT_ID, PARAM_VALUE) values ('2022-01-02',1, 34);
insert TEST_TABLE (DT, OBJECT_ID, PARAM_VALUE) values ('2022-01-03',1, 78);
insert TEST_TABLE (DT, OBJECT_ID, PARAM_VALUE) values ('2022-01-04',1, 11);
insert TEST_TABLE (DT, OBJECT_ID, PARAM_VALUE) values ('2022-01-05',1, 26);
insert TEST_TABLE (DT, OBJECT_ID, PARAM_VALUE) values ('2022-01-06',1, 11);
insert TEST_TABLE (DT, OBJECT_ID, PARAM_VALUE) values ('2022-01-07',1, 12);
insert TEST_TABLE (DT, OBJECT_ID, PARAM_VALUE) values ('2022-01-08',1, 74);
insert TEST_TABLE (DT, OBJECT_ID, PARAM_VALUE) values ('2022-01-01',2, 18);
insert TEST_TABLE (DT, OBJECT_ID, PARAM_VALUE) values ('2022-01-02',2, 96);
insert TEST_TABLE (DT, OBJECT_ID, PARAM_VALUE) values ('2022-01-03',2, 33);
insert TEST_TABLE (DT, OBJECT_ID, PARAM_VALUE) values ('2022-01-04',2, 77);
insert TEST_TABLE (DT, OBJECT_ID, PARAM_VALUE) values ('2022-01-05',2, 55);
insert TEST_TABLE (DT, OBJECT_ID, PARAM_VALUE) values ('2022-01-06',2, 28);
insert TEST_TABLE (DT, OBJECT_ID, PARAM_VALUE) values ('2022-01-07',2, 54);
insert TEST_TABLE (DT, OBJECT_ID, PARAM_VALUE) values ('2022-01-08',2, 16);
set @TARGET_DATE = '2022-01-08';
select
OBJECT_ID,
group_concat(if(DT = DATE_ADD(@TARGET_DATE, interval -1 day) , PARAM_VALUE, null)) as `dt-1`,
group_concat(if(DT = DATE_ADD(@TARGET_DATE, interval -2 day) , PARAM_VALUE, null)) as `dt-2`
from TEST_TABLE group by OBJECT_ID;
OBJECT_ID | dt-1 | dt-2 |
---|---|---|
1 | 12 | 11 |
2 | 54 | 28 |
SET @TARGET_DATE = '2022-01-08';
SELECT GROUP_CONCAT(DISTINCT CONCAT(
'GROUP_CONCAT(IF(DT="',DT,'", PARAM_VALUE, NULL)) AS "',DT,'"')
ORDER BY DT DESC
SEPARATOR ', \r\n' )
INTO @columns
FROM TEST_TABLE
WHERE DT >= DATE_ADD(@TARGET_DATE, interval -2 day)
AND DT <= DATE_ADD(@TARGET_DATE, interval -1 day);
SELECT CONCAT('SELECT OBJECT_ID,',@columns,'
FROM TEST_TABLE
GROUP BY OBJECT_ID;') INTO @sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
OBJECT_ID | 2022-01-07 | 2022-01-06 |
---|---|---|
1 | 12 | 11 |
2 | 54 | 28 |
SELECT @columns;
SELECT @sql;
@columns |
---|
GROUP_CONCAT(IF(DT="2022-01-07", PARAM_VALUE, NULL)) AS "2022-01-07", GROUP_CONCAT(IF(DT="2022-01-06", PARAM_VALUE, NULL)) AS "2022-01-06" |
@sql |
---|
SELECT OBJECT_ID,GROUP_CONCAT(IF(DT="2022-01-07", PARAM_VALUE, NULL)) AS "2022-01-07", GROUP_CONCAT(IF(DT="2022-01-06", PARAM_VALUE, NULL)) AS "2022-01-06" FROM TEST_TABLE GROUP BY OBJECT_ID; |