如何显示表结果列并在行上显示它

时间:2018-06-13 08:25:24

标签: php tabular

enter image description here

有人可以帮我创建一个表格,我可以将其他行用作列吗?

我的示例数据库如下所示:

|    NAME | DATE             |    TIME     |TYPE |
|    john    | 03-05-2017  |    06:00    | AM IN
|    john    | 03-05-2017  |    11:00    | AM OUT
|    john    | 03-05-2017  |    13:00    | PM IN
|    john    | 03-05-2017  |    16:00    | PM OUT

| john | 03-06-2017  | 06:00 | AM IN
| john | 03-06-2017  | 11:00 | AM OUT

| john | 03-07-2017  | 06:00 | AM IN
| john | 03-07-2017  | 11:00 | AM OUT
| john | 03-07-2017  | 13:00 | PM IN
| john | 03-07-2017  | 16:00 | PM OUT

如何在PHP表中显示如下:

|    DATE      | AM IN  |AM OUT   |    PM IN    | PMOUT
03-05-2017   06:00     |11:00        |   13:00      |16:00
03-06-2017   06:00     |11:00        |   NULL       | NULL
03-07-2017   06:00    |11:00         |    13:00      |16:00

我已上传图片,以便我可以更好地解释

1 个答案:

答案 0 :(得分:1)

我认为你只想要一个透视查询:

SELECT
    NAME,
    DATE,
    MAX(CASE WHEN TYPE = 'AM IN'  THEN TIME END) AS AM_IN,
    MAX(CASE WHEN TYPE = 'AM OUT' THEN TIME END) AS AM_OUT,
    MAX(CASE WHEN TYPE = 'PM IN'  THEN TIME END) AS PM_IN,
    MAX(CASE WHEN TYPE = 'PM OUT' THEN TIME END) AS PM_OUT
FROM yourTable
GROUP BY
    NAME, DATE;