gpt4 book ai didi

sql - 如何在同一表的同一列上连接具有不同where子句的SQL语句

转载 作者:IT王子 更新时间:2023-10-29 06:28:07 24 4
gpt4 key购买 nike

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

最佳答案

你可以这样做:

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

关于sql - 如何在同一表的同一列上连接具有不同where子句的SQL语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11681971/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com