SQL合并和选择一个结果

时间:2018-01-11 15:27:42

标签: sql sql-server select subquery aggregate-functions

我对同一个表有2个选择查询,这两个查询在select部分中只包含sum(),但在where子句中有所不同。我需要做的是将两个查询的结果相加。

示例查询:

SELECT SUM(amount) 
FROM EXAMPLETABLE
WHERE  IDATE BETWEEN '2017/01/01' AND '2017/12/31' AND SOMESTATUS = 0

SELECT SUM(otherAmount) 
FROM EXAMPLETABLE
WHERE  IDATE BETWEEN '2018/01/01' AND '2018/12/31' AND SOMESTATUS = 1

我需要的是像

SELECT SUM(amount+otherAmount)
FROM EXAMPLETABLE

在我的示例查询中选择了amountotherAmount

我试图关注this question,但我无法让它发挥作用。我还尝试用sub-select替换字段,但这不起作用,因为selects

中不允许aggregate function

4 个答案:

答案 0 :(得分:2)

这是一种简单的方法:

SELECT SUM(b.a)
FROM (
    SELECT SUM(amount) a
    FROM EXAMPLETABLE
    WHERE IDATE BETWEEN '2017/01/01'
            AND '2017/12/31'
        AND SOMESTATUS = 0

    UNION ALL

    SELECT SUM(otherAmount) a
    FROM EXAMPLETABLE
    WHERE IDATE BETWEEN '2018/01/01'
            AND '2018/12/31'
        AND SOMESTATUS = 1
    ) AS b

我刚刚在两个查询之间创建了一个联合并对结果求和。

答案 1 :(得分:1)

您可以执行此条件聚合。

SELECT SUM(case when IDATE BETWEEN '2017/01/01' AND '2017/12/31' AND SOMESTATUS = 0 then amount else 0 end) +
SUM(case when IDATE BETWEEN '2018/01/01' AND '2018/12/31' AND SOMESTATUS = 1 then amount else 0 end) 
FROM EXAMPLETABLE

答案 2 :(得分:0)

非常简单:

SELECT SUM((1-SOMESTATUS)*amount + SOMESTATUS*(otherAmount))
FROM EXAMPLETABLE
WHERE IDATE BETWEEN '2018-01-01' AND '2018-12-31'

...小心你的约会。我认为你必须用破折号替换斜杠

答案 3 :(得分:0)

我认为你可以在SQL Server中编写这个

SELECT
( SELECT SUM(amount) a FROM EXAMPLETABLE WHERE IDATE BETWEEN '2017/01/01' AND '2017/12/31' AND SOMESTATUS = 0 )
+
( SELECT SUM(otherAmount) a FROM EXAMPLETABLE WHERE IDATE BETWEEN 2018/01/01' AND '2018/12/31' AND SOMESTATUS = 1 )