我有两个查询,每个查询将输出2列。他们来自同一张桌子。
查询1
SELECT MONTH(DateOrdered) AS MONTH,SUM(Downpayment)AS total FROM transaction WHERE YEAR(DateOrdered) = YEAR('2018-12-00') AND Status = 'Ongoing' GROUP BY MONTH(DateOrdered)
MONTH-----total
10------------4590
12------------1497.5
查询2
SELECT MONTH(DateFinish) AS MONTH,SUM(Total-Downpayment)AS total FROM transaction WHERE YEAR(DateFinish) = YEAR('2018-12-00') AND Status = 'Complete' GROUP BY MONTH(DateFinish)
MONTH--------total
5-----------------1147.5
10----------------1647
12----------------1147.5
我想将两者和SUM结合起来,将2列称为total
例如
MONTH------------total
5--------------------1147.5
10--------------------6237
12--------------------2645
我现在有什么
SELECT MONTH(DateOrdered) AS MONTH,SUM(Downpayment) FROM transaction WHERE YEAR(DateOrdered) = YEAR('2018-12-00') AND Status = 'Ongoing' GROUP BY MONTH(DateOrdered) UNION SELECT MONTH(DateFinish) AS MONTH,SUM(Total-Downpayment) FROM transaction WHERE YEAR(DateFinish) = YEAR('2018-12-00') AND Status = 'Complete' GROUP BY MONTH(DateFinish)
显示
MONTH--------total
10----------------4590
12----------------1497.5
5-----------------1147.5
10----------------1647
12----------------1147.5
答案 0 :(得分:1)
此处使用的高级概念是:1)联合查询和2)子查询
类似于以下内容:
Select
sum(total) as totalByMonth,
month
from
(
SELECT
MONTH(DateOrdered) AS MONTH,
SUM(Downpayment)AS total
FROM
transaction
WHERE
YEAR(DateOrdered) = YEAR('2018-12-00')
AND Status = 'Ongoing'
GROUP BY
MONTH(DateOrdered)
Union
SELECT
MONTH(DateFinish) AS MONTH,
SUM(Total-Downpayment)AS total
FROM
transaction
WHERE
YEAR(DateFinish) = YEAR('2018-12-00')
AND Status = 'Complete'
GROUP BY
MONTH(DateFinish)
) subQuery1
group by
month