查询第一 sql 列减去另一列

query the first sql column to subtract the other column

我的 sql 中有这个 table,我想用 cus_count1 值减去 cus_count2 值。我想查询它,但我不确定该怎么做。

+---------------------+------------+------------+
|        Time         | cus_count1 | cus_count2 |
+---------------------+------------+------------+
| 2015-12-21 08:28:44 |          1 |          0 |
| 2015-12-21 08:29:09 |          2 |          1 |
| 2015-12-21 08:29:23 |          3 |          1 |
| 2015-12-21 08:29:35 |          4 |          1 |
| 2015-12-21 08:29:49 |          4 |          2 |
| 2015-12-21 08:30:09 |          5 |          2 |
| 2015-12-21 08:30:17 |          6 |          2 |
+---------------------+------------+------------+

这是我的 php 代码:

<?php

    $server = "localhost";
    $user = "root";
    $password = "";
    $database = "";

    $connection = mysql_connect($server,$user,$password);
    $db = mysql_select_db($database,$connection);

    $query1 = "SELECT time,  cus_count1 - cus_count2 AS cus_flow FROM new_tbl_cus";
    $result1 = mysql_query($query1);

     while($row = mysql_fetch_assoc($result1))
     {


        $dataset1[] = array(strtotime($row['time'])*1000,$row['cus_flow']);
        //echo strtotime($row['time'])*1000;

    }
?>

你只是想要简单的减法吗?如果是,你可以这样做:

select time, cus_count1 - cus_count2 as finalvalue
from tablename

我想您可能要求不同的东西,或者这真的是您要求的吗?在上面的语句中,finalvalue 是给 calculated/derived 列的人工列名(又名别名)。

使用

 SELECT *,  cus_count1 - cus_count2 as diff FROM [dbo].tablename

作为 SQL。

您将获得一个额外的列 Diff 作为结果集中的最后一列。

如果要为特定行减去,请在 table 或后续 table 列的主键上添加 WHERE 子句