如何使用sql查询在同一列中减去两行的值?

时间:2014-11-08 12:28:22

标签: sql

我想使用subtraction查询显示two个不同行中两个值的SQL

这是表结构:

------------------------------------
id | name | sub1 | sub2 | date
------------------------------------
1  | ABC  | 50   | 75   | 2014-11-07
2  | PQR  | 60   | 80   | 2014-11-08  

我想从2014-11-07之日减去日期2014-11-08主题标记。

输出应该像

一样
| sub1  | sub2 |
 ---------------
|   10  |   5  |

3 个答案:

答案 0 :(得分:14)

您可以使用连接来获取行,然后减去值:

SELECT(t2.sub1 - t1.sub1) AS sub1, (t2.sub2 - t1.sub2) AS sub2
FROM table t1 CROSS JOIN
     table t2
WHERE t1.date = '2014-11-08' AND t2.id = '2014-11-07';

答案 1 :(得分:2)

我觉得你遗漏了实际需求的一个重要部分,你可能想要按某个特定领域分组并返回相应的值,所以答案有限。您可以像上面的示例一样双重引用表,但如果您只能以某种方式仅引用表一次并且不需要索引查找,书签查找等,通常会更好。您通常可以使用简单聚合或窗口聚合来完成此

SELECT
  MAX(sub1) - MIN(sub1) AS sub1, 
  MAX(sub2) - MIN(sub2) AS sub2
FROM
  dbo.someTable;

http://sqlfiddle.com/#!6/75ccc/2

答案 2 :(得分:1)

交叉连接可能难以使用,因为它们以通常不直观的方式关联数据。这是我如何使用简单的默认值INNER JOIN

来实现的
WITH day1_info AS
    (SELECT sub1, sub2
     FROM mytable)
SELECT
    day2_info.sub1 - day1_info.sub1 AS sub1_difference,
    day2_info.sub2 - day1_info.sub2 AS sub2_difference,
FROM
    mytable AS day2_info JOIN day1_info
        ON day1_info.date = '2014-11-07'
        AND day2_info.date = '2014-11-08'

如果您想为多组日期执行此操作,您也可以这样做。只需稍微更改JOIN语句即可。 (请注意,在这种情况下,您可能还需要SELECT其中一个日期,以便了解每个结果适用于哪个时间段。)

WITH day1_info AS
    (SELECT sub1, sub2
     FROM mytable)
SELECT
    day2_info.date,
    day2_info.sub1 - day1_info.sub1 AS sub1_difference,
    day2_info.sub2 - day1_info.sub2 AS sub2_difference,
FROM
    mytable AS day2_info JOIN day1_info
        ON (day1_info.date::timestamp + '1 day') = day2_info.date::timestamp