我在sqlite中有2个语句
第一声明:
Select SUM(GrossQty) As GQTY, SUM(NetQty) As NQTY
From NSales
Where IMonth=5 And IYear=2012 And IDay>15
结果:
GQty NQty 30 25
第二声明
Select SUM(GrossQty) As GQTY, SUM(NetQty) As NQTY
From NSales
Where IMonth=6 And IYear=2012 And IDay<10
第二个结果:
GQty NQty 20 15
如何组合这些语句,以便将这些结果添加到一起?
期望的结果:
GQty NQty 50 40
答案 0 :(得分:8)
你可以这样做:
SELECT
SUM(a.GQTY) AS GrossQty,
SUM(a.NQTY) AS NQTY
FROM
(
SELECT SUM(GrossQty) AS GQTY, SUM(NetQty) AS NQTY
FROM NSales
WHERE IMonth = 5 AND IYear = 2012 AND IDay > 15
UNION ALL
SELECT SUM(GrossQty), SUM(NetQty)
FROM NSales
WHERE IMonth = 6 AND IYear = 2012 AND IDay < 10
) a
可替换地:
SELECT
a.GQTY + b.GQTY AS GQTY,
a.NQTY + b.NQTY AS NQTY
FROM
(
SELECT SUM(GrossQty) AS GQTY, SUM(NetQty) AS NQTY
FROM NSales
WHERE IMonth = 5 AND IYear = 2012 AND IDay > 15
) a
CROSS JOIN
(
SELECT SUM(GrossQty) AS GQTY, SUM(NetQty) NQTY
FROM NSales
WHERE IMonth = 6 AND IYear = 2012 AND IDay < 10
) b
或者您可以使用CASE
表达式,避免发出两个单独的子选择(难以阅读):
SELECT
SUM(
CASE WHEN (IMonth = 5 AND IYear = 2012 AND IDay > 15) OR
(IMonth = 6 AND IYear = 2012 AND IDay < 10) THEN
GrossQty
ELSE 0
END) AS GQTY,
SUM(
CASE WHEN (IMonth = 5 AND IYear = 2012 AND IDay > 15) OR
(IMonth = 6 AND IYear = 2012 AND IDay < 10) THEN
NetQty
ELSE 0
END) AS NQTY
FROM NSales