【问题标题】:How to get row values as columns using Sql Query CASE statement如何使用 Sql Query CASE 语句将行值作为列获取
【发布时间】:2020-08-06 12:25:18
【问题描述】:

我有一张桌子

s_id   student_name attendance_date status
1        student1     2020-01-01     P
2        student1     2020-01-02     P
3        student2     2020-01-01     P
4        student2     2020-01-02     A

我想要我的桌子

s_id    student_name   01-01-2020   02-01-2020
1       student1       P             P
2       student2       P             A

我尝试过使用 CASE WHEN 语句,但学生的名字不断重复。如何在不重复学生姓名的情况下得到结果?

【问题讨论】:

  • 如果后来有人添加了一个日期为 2020-04-23 的新行,你是不是突然想要一个新列?
  • 使用 php 我使用了日期过滤器。用户可以选择输入日期。
  • 考虑处理应用代码中数据显示的问题
  • id 在这种情况下似乎没有意义

标签: mysql sql group-by pivot case-when


【解决方案1】:

试试下面的,这里是DEMO。我没有包含s_id,因为在这里包含它没有任何意义。

select
    student_name,
    max(case when attendance_date='2020-01-01' then status end) as '01-01-2020',
    max(case when attendance_date='2020-01-02' then status end) as '01-02-2020'
from yourTable
group by
    student_name

【讨论】:

  • 没有group by 子句,这不是一个有效的查询。
  • 非常感谢您的回复。它显示sql错误:组函数的使用无效
【解决方案2】:

要在固定的日期列表上进行透视,您可以进行条件聚合:

select
    s_id, 
    student_name,
    max(case when attendance_date = '2020-01-01' then status end) `2020-01-01`,
    max(case when attendance_date = '2020-01-02' then status end) `2020-01-02`
from mytable
group by s_id, student_name
order by s_id

【讨论】:

    猜你喜欢
    • 2021-02-10
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    相关资源
    最近更新 更多