如何使用SQL查询在表中的两个字段之间进行减法

时间:2017-06-05 09:58:28

标签: mysql sql

我想使用SQL查询显示从两个不同列到第三列的两个值的减法。

这是表结构:

------------------------------------
id | subject | Time1 | Time2| Time3
------------------------------------
1  | String1 | 50    |  78  | 
2  | String2 | 60    |  99  |  
3  |         |       |      |

如果Time1和Time2都有数据并存储在Time3中,我想从Time1中减去Time2。

输出应该像

一样
------------------------------------
id | subject | Time1 | Time2| Time3
------------------------------------
1  | String1 | 50    |  78  |  28
2  | String2 | 60    |  99  |  39
3  |         |       |      |

谢谢!

8 个答案:

答案 0 :(得分:2)

试试这个

SELECT *, `Time2`-`Time1` AS `Time3` FROM `tablename`

答案 1 :(得分:2)

`SELECT 
     id, 
     subject, 
     Time1, 
     Time2, 
     IF( Time1 != '' AND Time2 != '', Time2-Time1, '') as Time3 
FROM tbl_time`

答案 2 :(得分:1)

SELECT
    id
    ,subject
    ,Time1
    ,Time2
    ,Time2-Time1 as Time3
FROM tbl

答案 3 :(得分:1)

假设Time1Time2是数字列,您可以使用简单的减法:

select id, subject, Time1, Time3, Time2 - Time1 as Time3 from myTable

答案 4 :(得分:1)

试试这个

select id, subject, Time1, Time2, Time2-Time1 as Time3  from mytable

答案 5 :(得分:0)

这会检查Time1Time2中是否存在数据:如果有足够的数据,Time3 = Time2 - Time1;否则它是null

select id, subject, Time1, Time2, 
   ifnull(Time1, null, ifnull(Time2, null, Time2 - Time1)) as Time3 
from myTable

答案 6 :(得分:0)

如果Time1和Time2是日期时间字段,那么您应该在MySQL中使用TIMEDIFF函数才能正确格式化Time3字段。

SELECT id, subject, Time1, Time2, TIMEDIFF(Time1, Time2) as Time3 
  FROM tbl

http://www.w3resource.com/mysql/date-and-time-functions/mysql-timediff-function.php

答案 7 :(得分:0)

尝试一下

SELECT id, subject, Time1, Time2, CONCAT(Time2 - Time1) AS Time3 FROM tabel