显示两列的组合数据并显示偶数列

时间:2017-09-28 02:26:54

标签: php mysql

我有一个包含以下格式数据的表

Counter

我正在寻找以下列格式输出数据的最佳查询。

state

如何生成如上所示的'routes'列,并且只能在某些'pin'上的偶数列上显示? 非常感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用以下方法在MySQL中实现此目的。看到它正常工作SQL Fiddle

MySQL 5.6架构设置

CREATE TABLE Table1
    (`pin` int, `name` varchar(7), `scan_Time` time, `scan_location` varchar(8))
;

INSERT INTO Table1
    (`pin`, `name`, `scan_Time`, `scan_location`)
VALUES
    (1, 'Albert', '09:25:53', 'Office A'),
    (1, 'Albert', '10:26:12', 'Office B'),
    (2, 'Barry', '08:26:21', 'Office C'),
    (2, 'Barry', '09:21:57', 'Office B'),
    (2, 'Barry', '10:31:17', 'Office B'),
    (2, 'Barry', '12:21:44', 'Office A'),
    (3, 'Cantika', '07:38:10', 'Office B'),
    (3, 'Cantika', '10:02:28', 'Office A')
;

查询1

SELECT
   pin,name,scan_time,scan_location, route
FROM (
      SELECT
            @row_num := (@row_num+1)%2  AS RowNumber
          , t1.*
          , IF((@row_num+1)%2=1,concat(@prev_value , ' ', scan_location),'') route
          , @prev_value := t1.scan_location
      FROM table1 t1
      CROSS JOIN (
              SELECT @row_num :=0,  @prev_value := ''
            ) vars
      ORDER BY pin, scan_time
     ) d

<强> Results

| pin |    name | scan_time | scan_location |             route |
|-----|---------|-----------|---------------|-------------------|
|   1 |  Albert |  09:25:53 |      Office A |                   |
|   1 |  Albert |  10:26:12 |      Office B | Office A Office B |
|   2 |   Barry |  08:26:21 |      Office C |                   |
|   2 |   Barry |  09:21:57 |      Office B | Office C Office B |
|   2 |   Barry |  10:31:17 |      Office B |                   |
|   2 |   Barry |  12:21:44 |      Office A | Office B Office A |
|   3 | Cantika |  07:38:10 |      Office B |                   |
|   3 | Cantika |  10:02:28 |      Office A | Office B Office A |
相关问题