英文:
How can I transform a SQL table?
问题
以下是翻译好的部分:
NumberOfLesson | Monday | Tuesday | Wednesday | Thursday | Friday |
---|---|---|---|---|---|
1 | 0 | 数学 | 艺术 | 0 | 0 |
2 | 0 | 数学 | 历史 | 0 | 0 |
... | ... | ... | ... | ... | ... |
英文:
There is the following table for one teacher:
NumberOfLesson | DayOfWeek | LessonName |
---|---|---|
1 | Tuesday | Maths |
2 | Tuesday | Maths |
3 | Tuesday | PE |
1 | Wednesday | Art |
2 | Wednesday | History |
... | ... | ... |
Is there any easy way to convert this table into the following one?
NumberOfLesson | Monday | Tuesday | Wednesday | Thursday | Friday |
---|---|---|---|---|---|
1 | 0 | Maths | Art | 0 | 0 |
2 | 0 | Math | History | 0 | 0 |
... | ... | ... | ... | ... | ... |
I tried to use PIVOT
but can't figure out how to do it for an "infinite" number of rows but a finite number of columns.
答案1
得分: 4
我们可以尝试使用透视查询,借助 COALESCE()
函数:
SELECT
NumberOfLesson,
COALESCE(MAX(CASE WHEN DayOfWeek = 'Monday'
THEN LessonName END), '0') AS 星期一,
COALESCE(MAX(CASE WHEN DayOfWeek = 'Tuesday'
THEN LessonName END), '0') AS 星期二,
COALESCE(MAX(CASE WHEN DayOfWeek = 'Wednesday'
THEN LessonName END), '0') AS 星期三,
COALESCE(MAX(CASE WHEN DayOfWeek = 'Thursday'
THEN LessonName END), '0') AS 星期四,
COALESCE(MAX(CASE WHEN DayOfWeek = 'Friday'
THEN LessonName END), '0') AS 星期五
FROM yourTable
GROUP BY NumberOfLesson
ORDER BY NumberOfLesson;
英文:
We can try using a pivot query here with the help of COALESCE()
:
<!-- language: sql -->
SELECT
NumberOfLesson,
COALESCE(MAX(CASE WHEN DayOfWeek = 'Monday'
THEN LessonName END), '0') AS Monday,
COALESCE(MAX(CASE WHEN DayOfWeek = 'Tuesday'
THEN LessonName END), '0') AS Tuesday,
COALESCE(MAX(CASE WHEN DayOfWeek = 'Wednesday'
THEN LessonName END), '0') AS Wednesday,
COALESCE(MAX(CASE WHEN DayOfWeek = 'Thursday'
THEN LessonName END), '0') AS Thursday,
COALESCE(MAX(CASE WHEN DayOfWeek = 'Friday'
THEN LessonName END), '0') AS Friday
FROM yourTable
GROUP BY NumberOfLesson
ORDER BY NumberOfLesson;
答案2
得分: 2
以下是翻译好的部分,代码部分不做翻译:
SELECT NumberOfLesson,
Monday = COALESCE(Monday, '0'),
Tuesday = COALESCE(Tuesday, '0'),
Wednesday = COALESCE(Wednesday, '0'),
Thursday = COALESCE(Thursday, '0'),
Friday = COALESCE(Friday, '0')
FROM dbo.TheTable
PIVOT
(
MAX(LessonName)
FOR DayOfWeek IN (Monday,Tuesday,Wednesday,Thursday,Friday)
) AS p
ORDER BY NumberOfLesson;
英文:
You've got a solution with conditional aggregation but in case you're still wondering how to work it out with PIVOT
:
SELECT NumberOfLesson,
Monday = COALESCE(Monday, '0'),
Tuesday = COALESCE(Tuesday, '0'),
Wednesday = COALESCE(Wednesday, '0'),
Thursday = COALESCE(Thursday, '0'),
Friday = COALESCE(Friday, '0')
FROM dbo.TheTable
PIVOT
(
MAX(LessonName)
FOR DayOfWeek IN (Monday,Tuesday,Wednesday,Thursday,Friday)
) AS p
ORDER BY NumberOfLesson;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论