我想知道如何在表格中添加子查询的结果。例如,我想在一个语句中添加以下两个查询。
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 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 (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