如何在同一个表的同一列上使用不同的where子句连接SQL语句

时间:2012-07-27 05:29:10

标签: sql sqlite

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

1 个答案:

答案 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