选择Case以获取MAX值,并在row为null时输出不同的值

时间:2014-11-20 23:37:17

标签: mysql case

我正在尝试检查行是否为null然后如果它的null输出值为0.000然后如果它没有得到MAX值,我尝试了几个case语句但我不能让它正常工作,即时通讯总是出现语法错误。

这是我在测试前使用的原始查询:

SELECT FROM_UNIXTIME(t_stamp/1000, '%m/%d/%Y %l:%i %p') as t_stamp,
  ROUND(MAX(CASE WHEN id = "0123" THEN value END),3) C1, 
  ROUND(MAX(CASE WHEN id = "0124" THEN value END),3) C2,    
  ROUND(MAX(CASE WHEN id = "0125" THEN value END),3) C3,   
  ROUND(MAX(CASE WHEN id = "0126" THEN value END),3) C4,  
  ROUND(MAX(CASE WHEN id = "0127" THEN value END),3) C5, 
  ROUND(MAX(CASE WHEN id = "0128" THEN value END),3) C6 

FROM table1
WHERE id IN ("0123", "0124", "0125", "0126", "0127", "0128") and
FROM_UNIXTIME(t_stamp/1000) BETWEEN "2014-11-01 09:00:00" AND "2014-11-01 12:00:00"
GROUP BY DATE(FROM_UNIXTIME(t_stamp/1000)), HOUR(FROM_UNIXTIME(t_stamp/1000)), MINUTE(FROM_UNIXTIME(t_stamp/1000)) DIV 1

我测试的其中一个查询是我将选择查询更改为此。 (因为我之前只测试过这个,我尝试只获得一列的输出,但仍然是语法错误)

SELECT FROM_UNIXTIME(t_stamp/1000, '%m/%d/%Y %l:%i %p') as t_stamp,

    CASE id
          WHEN 0123 THEN ROUND(MAX(value),3)
          CASE WHEN id
          WHEN 0123 AND IS NULL THEN 0.000
        END
      END AS C1

FROM table1
WHERE id IN ("0123") and
FROM_UNIXTIME(t_stamp/1000) BETWEEN "2014-11-01 09:00:00" AND "2014-11-01 12:00:00"
GROUP BY DATE(FROM_UNIXTIME(t_stamp/1000)), HOUR(FROM_UNIXTIME(t_stamp/1000)), MINUTE(FROM_UNIXTIME(t_stamp/1000)) DIV 1

我希望你们能帮助我。谢谢!

1 个答案:

答案 0 :(得分:0)

您的CASE声明应该是

CASE WHEN id = 0123 THEN ROUND(MAX(value),3)
   WHEN id = 0123 OR id IS NULL THEN 0.000
  ELSE NULL
  END AS C1

每条评论

CASE WHEN id = 0123 THEN ROUND(MAX(value),3)
   WHEN id = 0123 AND value IS NULL THEN 0.000
  ELSE NULL
  END AS C1