我在 sqlite 中有一张表
| id | Weekday | reading_datetime |
|----+-----------+------------------|
| 1 | Sunday | datetime_value_1 |
| 2 | monday | datetime_value_2 |
| 3 | tuesday | datetime_value_3 |
| 4 | wednesday | datetime_value_4 |
| 5 | thursday | datetime_value_5 |
| 6 | friday | datetime_value_6 |
| 7 | saturday | datetime_value_7 |
| 8 | sunday | datetime_value_8 |
| 9 | monday | datetime_value_9 |
| .. | .. | .. |
一周中的每一天的表中都有几年的日期时间值 我想要的是转置七列中的值 像这样:
| sunday | monday | tuesday | wednesday | thursday | friday | saturday |
|-------------+-------------+-------------+-------------+-------------+-------------+-------------|
| dt_value_1 | dt_value_2 | dt_value_3 | dt_value_4 | dt_value_5 | dt_value_6 | dt_value_7 |
| dt_value_8 | dt_value_9 | dt_value_10 | dt_value_11 | dt_value_12 | dt_value_13 | dt_value_14 |
| dt_value_15 | dt_value_16 | dt_value_17 | dt_value_18 | dt_value_19 | dt_value_20 | dt_value_21 |
| dt_value_22 | dt_value_23 | dt_value_24 | dt_value_25 | dt_value_26 | dt_value_27 | dt_value_28 |
有人可以帮忙吗?
假设一周中的每一天总是有每周记录,我们可以在
ROW_NUMBER
的帮助下尝试旋转方法:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY Weekday ORDER BY id) rn
FROM yourTable
)
SELECT
MAX(CASE WHEN Weekday = 'sunday' THEN reading_datetime END) AS sunday,
MAX(CASE WHEN Weekday = 'monday' THEN reading_datetime END) AS monday,
MAX(CASE WHEN Weekday = 'tuesday' THEN reading_datetime END) AS tuesday,
MAX(CASE WHEN Weekday = 'wednesday' THEN reading_datetime END) AS wednesday,
MAX(CASE WHEN Weekday = 'thursday' THEN reading_datetime END) AS thursday,
MAX(CASE WHEN Weekday = 'friday' THEN reading_datetime END) AS friday,
MAX(CASE WHEN Weekday = 'saturday' THEN reading_datetime END) AS saturday
FROM cte
GROUP BY (rn - 1) / 7
ORDER BY (rn - 1) / 7;