如何在MySQL

时间:2017-09-21 12:43:33

标签: mysql sql

我正在尝试获取此MySQL Select Query中的3列总数,我得到的结果正确,我不知道如何获得总和(Party1 + Party2 + Party3)

我试图将每个分成自己的选择,没有结果。

由于

SELECT
sum(`InvoiceItem`.`qty`) AS `Quantity`,
IF(sum(qty) < 4999, sum(qty) * 2500, sum(qty) * 5000) AS party1,
IF(sum(qty) < 4999, sum(qty) * 2000, sum(qty) * 4000) AS party2,
IF(sum(qty) < 4999, sum(qty) * 500, sum(qty) * 1000) AS party3
     FROM `InvoiceItem`
 LEFT JOIN `Invoice` ON `InvoiceItem`.`parent` = `Invoice`.`name`
 LEFT JOIN `Ticket` ON `Invoice`.`wbt` = `Ticket`.`id`
 WHERE 
`InvoiceItem`.`status` = 1
 AND 
 MONTH(posting_date) = MONTH(CURDATE()) -2

 //Result of Query above
---------------------------------------------
 Quantity | party1 | party2 | Party3 | Total = (Party1+Party2+Party3)
--------------------------------------------- 
 5000     | 1000   | 4000   | 5000   | ??

1 个答案:

答案 0 :(得分:3)

这应该有效:

SELECT sum(res.Quantity + res.party1 + res.party2 + res.party3) as total, 
res.Quantity,
res.party1, 
res.party2, 
res.party3 
FROM (
SELECT
sum(`InvoiceItem`.`qty`) AS `Quantity`,
IF(sum(qty) < 4999, sum(qty) * 2500, sum(qty) * 5000) AS party1,
IF(sum(qty) < 4999, sum(qty) * 2000, sum(qty) * 4000) AS party2,
IF(sum(qty) < 4999, sum(qty) * 500, sum(qty) * 1000) AS party3
     FROM `InvoiceItem`
 LEFT JOIN `Invoice` ON `InvoiceItem`.`parent` = `Invoice`.`name`
 LEFT JOIN `Ticket` ON `Invoice`.`wbt` = `Ticket`.`id`
 WHERE 
`InvoiceItem`.`status` = 1
 AND 
 MONTH(posting_date) = MONTH(CURDATE()) -2
 ) as res;