mysql - sql行值作为列?

标签 mysql sql

我有一个这样的表:

| calendar_week | task       | person |
| 1             | cooking    | Bernd  |
| 1             | cleaning   | Julia  |
| 2             | carwashing | Bernd  |
| 2             | cleaning   | James  |

是否有可能得到这样的输出:

| calendar_week | cooking | cleaning | carwashing |
| 1             | Bernd   | Julia    |            |
| 2             |         | James    | Bernd      |

因此不同的任务应该成为列,并且任务是“随机的”。

最佳答案

您可以使用条件聚合:

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,或者如 Strawberry 所评论的那样,在应用程序而不是数据库中处理数据透视。

关于mysql - sql行值作为列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58689556/

相关文章:

mysql - 查找与查询匹配的最后插入的行

php - 在 PHP 中连接到两个不同的数据库?

sql - Django多对多: Best way to get elements in one related query set but exclude elements in other related query sets?

mysql - 这个 "no data"警告来自哪里? (光标循环)

php - 如何使用php从手机获取手机收件箱消息到数据库?

php - 根据IP地址显示动态PHP内容

c# - Linq 的 Column In (Select ...) 语句

mysql - NOT IN 不工作的 SQL

php - PDO 绑定(bind)参数问题

mysql - 使用索引使sql查询更快