【问题标题】:is there anyway to display single column data into multiple columns无论如何将单列数据显示到多列中
【发布时间】:2019-10-20 13:03:31
【问题描述】:

我试图这样做,但对我来说是不可能的。解决方案我只需要将单列数据显示到当前表的多列中。例如 column [status] 3 记录 {present,late,absent} 显示 3 列和单行,以防止 3 行

SELECT tid,status, COUNT(status) AS counter FROM `attend_teacher` GROUP BY status,tid ORDER by tid

+-----+---------+---------+
| tid | status  | counter |
+-----+---------+---------+
|   1 | absent  |       1 |
|   1 | present |       2 |
|   1 | late    |       1 |
|   3 | late    |       1 |
+-----+---------+---------+

我想通过分组 tid 显示的结果

+-----+---------+---------+--------+
| tid | Present | late    | absent |
+-----+---------+---------+--------+
|   1 |    2    |    1    |    1   |
+-----+---------+---------+--------+
|   3 |    0    |    1    |    0   |
+-----+---------+---------+--------+

表结构

SELECT * FROM `attend_teacher`;
+----+-----+----------+---------+---------+----------------+
| id | tid | day      | status  | subject | date_created   |
+----+-----+----------+---------+---------+----------------+
|  1 |   1 | Saturday | present | 1,5     | 8 May 2019     |
|  2 |   1 | Saturday | present | 1,1,5,2 | 8 October 2019 |
|  3 |   1 | Saturday | absent  | 1,1,5,2 | 9 October 2019 |
|  4 |   1 | Saturday | late    | 1,1,5,2 | 9 October 2019 |
|  5 |   3 | Saturday | late    | 1,3,5,4 | 9 October 2019 |
+----+-----+----------+---------+---------+----------------+
5 rows in set (0.00 sec)

【问题讨论】:

  • SQL Server != MySQL,请仅标记您实际使用的 RDBMS。谢谢。
  • “为什么我要求 OP 不标记与问题无关的 RDBMS” 一些主题启动者可能会认为添加更多标签可能会更快地帮助他们这个问题在更多列表中可见,这里的 PHP 和 Javascript 标记也完全不需要接缝......无论如何@Larnu 我正在删除这些健谈的 cmets ;-) ..

标签: mysql sql database sum pivot


【解决方案1】:

您可以使用条件聚合来透视数据集:

select
    tid,
    sum(case when status = 'present' then 1 else 0 end) present,
    sum(case when status = 'late' then 1 else 0 end) late,
    sum(case when status = 'absent ' then 1 else 0 end) absent 
from attend_teacher
group by tid

【讨论】:

  • 感谢您帮助解决此问题
  • 如果它回答了这个问题,@Keynan,考虑接受它作为解决方案。
猜你喜欢
  • 1970-01-01
  • 2012-10-28
  • 1970-01-01
  • 2014-10-07
  • 1970-01-01
  • 2011-12-13
  • 1970-01-01
  • 1970-01-01
  • 2017-12-09
相关资源
最近更新 更多