1

我想知道如何在表格中添加子查询的结果。例如,我想在一个语句中添加以下两个查询。

SELECT SUM(A) - (SELECT SUM(B) FROM MyTable WHERE C<A))
FROM MyTable WHERE B>C;

SELECT SUM(B) - (SELECT SUM(C) FROM MyTable WHERE D<F))
FROM MyTable WHERE B=C;
4

1 回答 1

3

您实际上可以将它们加在一起:

SELECT (SELECT SUM(A) - (SELECT SUM(B) FROM MyTable WHERE C<A))
                         FROM MyTable WHERE B>C)  
        +
        (SELECT SUM(B) - (SELECT SUM(C) FROM MyTable WHERE D<F))
                          FROM MyTable WHERE B=C)

如同:

SELECT 5 + 3

您也可以使用一些 CASE 语句在没有子查询的情况下执行此操作,或者至少使其更清晰,例如:

SELECT SUM(CASE WHEN B > C THEN A ELSE 0 END) - SUM(CASE WHEN C < A THEN B ELSE 0 END)
       +
       SUM(CASE WHEN B = C THEN B ELSE 0 END) - SUM(CASE WHEN D < F THEN C ELSE 0 END)
FROM MyTable
于 2013-06-12T17:14:43.650 回答