6

我在 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
4

1 回答 1

9

你可以做:

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
于 2012-07-27T05:45:12.850 回答