How to avoid 0 values using MIN and MAX function in SQL?

那年仲夏 提交于 2019-12-11 17:16:30

问题


I have table like this:

Running    Date
  128      1/1/2018
  700      6/11/2018
  900      6/11/2018
  300      6/11/2018

If same dates then pick minimum value and maximum value and get difference from "RUNNING" Column. If only one date then do nothing and get same value

Query:

SELECT MAX(RUNNING) - MIN(RUNNING) "RUNNING", DATE
FROM TABLE
GROUP BY DATE;

I got following results:

Running    Date
  0        1/1/2018
  600      6/11/2018

But i want "128" value with "1/1/2018" date but this give 0 value

How to solve this?


回答1:


Include a CASE statement.

SELECT
     CASE
          WHEN MAX(running) = MIN(running) THEN MAX(running)
          ELSE MAX(running) - MIN(running)
     END
"RUNNING",
     dt
FROM t
GROUP BY dt;


来源:https://stackoverflow.com/questions/53588099/how-to-avoid-0-values-using-min-and-max-function-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!