将唯一列的多行组合为单行

时间:2013-05-16 01:26:09

标签: mysql grouping

我有一个跟踪应用程序返回代码的表。我试图弄清楚如何格式化查询以将每天的返回码返回到单行。以下是示例表:

ID  COMPUTER    RETURNCODE  DATE
--  --------    ----------  ----
1   computer1   0           May, 15 2013 00:00:00+0000
2   computer1   1           May, 16 2013 00:00:00+0000
3   computer1   1           May, 17 2013 00:00:00+0000
4   computer2   0           May, 15 2013 00:00:00+0000
5   computer2   4           May, 16 2013 00:00:00+0000
6   computer2   4           May, 17 2013 00:00:00+0000
7   computer3   0           May, 15 2013 00:00:00+0000
8   computer3   8           May, 16 2013 00:00:00+0000
9   computer3   0           May, 17 2013 00:00:00+0000

以下是我想通过查询获得的输出:

COMPUTER    2013-05-15    2013-05-16    2013-05-17
--------    ----------    ----------    ----------
computer1       0             1             1
computer2       0             4             4
computer3       0             8             0

我在这里通过sqlfiddle创建了一个示例: SQL小提琴示例:http://sqlfiddle.com/#!2/44687/1/0

感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

这称为“旋转”数据。以下是在MySQL中执行此操作的方法:

SELECT computer,
       max(case when date = '2013-05-15' then returncode end),
       max(case when date = '2013-05-16' then returncode end),
       max(case when date = '2013-05-17' then returncode end)
FROM returncodes
group by computer