mysql - 如何将列结果转换为 SQL 中的列标题?

标签 mysql sql select pivot sql-view

我有下表:

Sample
  id PK

Test
  id PK
  name varchar

Section
  id PK
  name varchar


TestSection
  id PK
  test_id FK
  section_id FK

SampleTestResult
  id PK
  sample_id FK
  test_section_id FK
  result

当我执行以下查询时:

  SELECT DISTINCT
   s.id as sample_id, ts.name as test, str.result
  FROM sample s 
  JOIN sample_test_result str ON s.id=str.sample_id
  JOIN test_section ts ON str.test_section_id=ts.id
  JOIN section sec ON ts.section_id=sec.id

我得到一个如下所示的表格:

| sample_id | test       | result    |
--------------------------------------
|    1      |  t1        |   fail    |
|    1      |  t2        |   pos     |      
|    2      |  t1        |   neg     |
|    2      |  t3        |   rpt     |
|    3      |  t2        |   pos     |
|    3      |  t4        |   pos     |    

但是我希望最终得到这样的表格:

| sample_id | t1    | t2    | t3    | t4    |
--------------------------------------------
|    1      | fail  | pos   | NULL  | NULL  |
|    2      | neg   | NULL  | rpt   | NULL  |
|    3      | NULL  | pos   | NULL  | pos   |

如何在 SQL 中转置表 - 这在查询中可能吗?或者它必须是一个sql View ?

最佳答案

对于 MySQL,解决此问题的典型方法是使用条件聚合:

SELECT 
    s.id as sample_id,  
    MAX(CASE WHEN ts.name = 't1' THEN str.result END) as t1,
    MAX(CASE WHEN ts.name = 't2' THEN str.result END) as t2,
    MAX(CASE WHEN ts.name = 't3' THEN str.result END) as t3,
    MAX(CASE WHEN ts.name = 't4' THEN str.result END) as t4 
FROM 
    sample s 
    JOIN sample_test_result str ON s.id=str.sample_id
    JOIN test_section ts ON str.test_section_id=ts.id
    JOIN section sec ON ts.section_id=sec.id
GROUP BY s.id

关于mysql - 如何将列结果转换为 SQL 中的列标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54714181/

相关文章:

mysql - 如何选择特定客户?

javascript - 没有 jQuery 或 Ajax 的链式选择

mysql - 列出参与项目的所有员工的部门名称

如果 MAX() 等于当前行 SUM() 聚合值,MySQL 如何选择 1?

mysql - 查看存储过程的代码但得到截断的定义

mysql - 我遇到了 SQL 连接和计数问题

php - Utf8、瑞典字符、Doctrine、Mysql 和 Json 序列化

mysql - 选择子行中的列具有特定值的行?

mysql - SQL Group By -- 自定义聚合函数 : max minus a value that differs in each group

css - Angular Material 选择选项宽度?