[英]sql row value as column?
我有一张这样的桌子:
| calendar_week | task | person |
| 1 | cooking | Bernd |
| 1 | cleaning | Julia |
| 2 | carwashing | Bernd |
| 2 | cleaning | James |
是否有可能像这样获得 output:
| calendar_week | cooking | cleaning | carwashing |
| 1 | Bernd | Julia | |
| 2 | | James | Bernd |
所以不同的任务应该成为列并且任务是“随机的”。
解决方案之一是使用连接。
select t1.tableA, coalesce(t2.person, '') as cooking
, coalesce(t3.person, '') as cleaning
, coalesce(t4.person, '') as carwashing
from (select distinct calendarweek from tableA) t1
left join tableA t2 on t2.calendarweek = t1.calendarweek and t2.task = 'cooking'
left join tableA t3 on t3.calendarweek = t1.calendarweek and t3.task = 'cleaning'
left join tableA t4 on t4.calendarweek = t1.calendarweek and t4.task = 'carwashing'
您可以使用条件聚合:
select
calendar_week,
max(case when task = 'cooking' then person end) cooking,
max(case when task = 'cleaning' then person end) cleaning,
max(case when task = 'carwashing' then person end) carwashing
from mytable
group by calendar_week
这适用于固定的任务列表,因为 SQL 查询必须返回固定的、预定义的列列表。 如果您要处理数量不可预测的任务,那么您将需要使用动态 SQL,或者,正如草莓所评论的那样,在您的应用程序而不是数据库中处理旋转。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.