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