如何水平查询显示数据?

时间:2019-11-20 03:06:58

标签: mysql sql database phpmyadmin

这是我表中的数据

id  id_mst_tag  value  time      date
1   1           100    16:18:25  2019-10-04
2   2           300    14:10:12  2019-10-04
3   1           90     18:11:22  2019-10-04
4   2           299    18:15:34  2019-10-04
5   1           98     20:13:45  2019-10-04
6   2           311    20:18:25  2019-10-04
7   3           OFF    22:13:21  2019-10-04

我想这样水平显示

id_mst_tag 14:00 16:00 18:00 20:00 22:00
1          NULL  100   90    98    NULL
2          300   NULL  299   311   NULL    
3          NULL  NULL  NULL  NULL  OFF

我该怎么做?请帮助

1 个答案:

答案 0 :(得分:0)

您可以考虑以下GROUP BY和CASE组合以获得所需的输出。

  

注意:“值”列中有“整数”和“文本”值,这是不现实的。希望在表中有NULL代替OFF。无论如何,您可以在“值”列中对格式正确的数据应用以下逻辑。

SELECT id_mst_tag,
SUM(CASE WHEN HOUR(time) = 14 THEN Value ELSE 0 END) `14:00`,
SUM(CASE WHEN HOUR(time) = 16 THEN Value ELSE 0 END) `16:00`,
SUM(CASE WHEN HOUR(time) = 18 THEN Value ELSE 0 END) `18:00`,
SUM(CASE WHEN HOUR(time) = 20 THEN Value ELSE 0 END) `20:00`,
SUM(CASE WHEN HOUR(time) = 22 THEN Value ELSE 0 END) `22:00`
FROM your_table
GROUP BY id_mst_tag

但是,如果数据库中存在“ OFF”,则可以尝试以下以下选项,并进行如下所示的另一种数据强制转换-

SELECT id_mst_tag,
SUM(CASE WHEN HOUR(time) = 14 THEN (CASE WHEN Value = 'OFF' THEN 0 ELSE CONVERT(Value,UNSIGNED INTEGER) END) ELSE 0 END) `14:00`,
SUM(CASE WHEN HOUR(time) = 16 THEN (CASE WHEN Value = 'OFF' THEN 0 ELSE CONVERT(Value,UNSIGNED INTEGER) END) ELSE 0 END) `16:00`,
SUM(CASE WHEN HOUR(time) = 18 THEN (CASE WHEN Value = 'OFF' THEN 0 ELSE CONVERT(Value,UNSIGNED INTEGER) END) ELSE 0 END) `18:00`,
SUM(CASE WHEN HOUR(time) = 20 THEN (CASE WHEN Value = 'OFF' THEN 0 ELSE CONVERT(Value,UNSIGNED INTEGER) END) ELSE 0 END) `20:00`,
SUM(CASE WHEN HOUR(time) = 22 THEN (CASE WHEN Value = 'OFF' THEN 0 ELSE CONVERT(Value,UNSIGNED INTEGER) END) ELSE 0 END) `22:00`
FROM your_table
GROUP BY id_mst_tag;