如何从表中返回多个列?
我的课程表:
|课程| PersId | Taskid |状态|
计算机< >用户1<> 1< >证实
计算机< > User2<> 1< 1>未经证实的
计算机< > User3<> 1< 1>未经证实的
计算机< > User1<> 2< 2>证实
计算机< > User2<> 2< 2>证实
计算机< > User3<> 2< 2>未确认
我希望它像这样返回:
| PersId | Task_1 | Task_2 |
User1<>确认< >证实
User2<>未经证实的<>证实
用户3<>未经证实的<>未确认
问题2:
我的桌子里还有其他课程(数学,英语等),课程多于两个。我是否需要使用某种迭代来返回任务列?因为我不想为每个单一课程(超过100)制作SQL查询。
提前致谢
答案 0 :(得分:3)
您可以使用CASE
和聚合:
select persid,
max(case when taskid = 1 then status end) as Task1,
max(case when taskid = 2 then status end) as Task2
from course
group by persid
如果您想要包含课程信息:
select persid,
course,
max(case when taskid = '1' then status end) as Task1,
max(case when taskid = '2' then status end) as Task2
from course
group by persid, course
order by course, persid
如果您的任务数量未知,那么您可以使用prepared statement动态生成此任务:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when taskid = ''',
taskid,
''' then status end) AS Task_',
taskid
)
) INTO @sql
FROM course;
SET @sql = CONCAT('SELECT persid, course, ', @sql, '
FROM course
group by persid, course
order by course, persid');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
答案 1 :(得分:0)
像这样:
SELECT
PersId,
MAX(CASE WHEN Taskid = 1 THEN Status END) AS Task_1,
MAX(CASE WHEN Taskid = 2 THEN Status END) AS Task_2
FROM Courses
GROUP BY persID
答案 2 :(得分:0)
使用PIVOTE男人的力量
PIVOT通过将表达式中一列中的唯一值转换为输出中的多个列来旋转表值表达式,并在最终输出中需要的任何剩余列值上执行聚合。
SELECT Course, PersId, [1] AS [Task_1], [2] AS [Task_2]
FROM
(
SELECT Course, PersId, TaskId, [Status]
FROM t2
) as a
PIVOT
(
MAX([Status])
FOR TaskId IN ([1], [2])
) as b