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

博客围绕SQL查询展开,给出表结构,包含id、subject、Time1、Time2和Time3列。需求是当Time1和Time2都有数据时,用Time2减去Time1,并将结果存储在Time3列。最后提供了实现该功能的SQL解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I want to display the subtraction of two values from two different columns to a third column using a SQL query.

This is the table structure:

------------------------------------

id | subject | Time1 | Time2| Time3

------------------------------------

1 | String1 | 50 | 78 |

2 | String2 | 60 | 99 |

3 | | | |

I want to subtract Time2 from Time1 if both Time1 and Time2 has data and store in Time3.

Output should be like as

------------------------------------

id | subject | Time1 | Time2| Time3

------------------------------------

1 | String1 | 50 | 78 | 28

2 | String2 | 60 | 99 | 39

3 | | | |

Thanks!

解决方案`SELECT

id,

subject,

Time1,

Time2,

IF( Time1 != '' AND Time2 != '', Time2-Time1, '') as Time3

FROM tbl_time`