【问题标题】:MySQL query to move row data into separate columns?MySQL查询将行数据移动到单独的列中?
【发布时间】:2021-01-17 11:05:25
【问题描述】:

假设我有一个包含一堆测试数据的表格,其中每一行都有一个设备号、测试号和测试结果。

|--------------------------------|
| device | test_number |  result |
|--------------------------------|
|    1   |      1      |  12.4   |
|--------------------------------|
|    1   |      2      |  13.2   |
|--------------------------------|
|    1   |      3      |  16.0   |
|--------------------------------|
|    1   |      4      |  88.4   |
|--------------------------------|
|    2   |      1      |  10.1   |
|--------------------------------|
|    2   |      2      |  9.3    |
|--------------------------------|
|    2   |      3      |  1.01   |
|--------------------------------|
|    2   |      4      |  3.4    |
|--------------------------------|

我想输出一个报告电子表格。所以我需要某种可以输出这种格式的表的 MySQL select 语句。

|------------------------------------------|
| test_number | result_dev1 |  result_dev2 |
|------------------------------------------|
|      1      |     12.4    |     10.1     |
|------------------------------------------|
|      2      |     13.2    |      9.3     |
|------------------------------------------|
|      3      |     16.0    |     1.01     |
|------------------------------------------|
|      4      |     88.4    |      3.4     |
|------------------------------------------|

我不知道该怎么做,尽管它看起来应该是直截了当的。有没有像这样将行条目分组到新列的好技巧?

【问题讨论】:

    标签: mysql sql group-by pivot


    【解决方案1】:

    对于固定的设备列表,可以做条件聚合:

    select test_number,
        max(case when device = 1 then result end) as result_dev1,
        max(case when device = 2 then result end) as result_dev2
    from mytable
    group by test_number
    

    【讨论】:

      猜你喜欢
      • 2011-05-10
      • 1970-01-01
      • 2019-12-29
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多