如何合并检查相同标志列但值不同的2个查询

时间:2018-04-18 10:00:21

标签: mysql sql

我有2个查询,我用它根据标志值

获取值的总和
SELECT SUM(stock_deliveries.stockValue) AS stockValues1
FROM `stock_deliveries`
LEFT JOIN `delivery` ON `delivery`.`pk_deliveryId`  = `stock_deliveries`.`fk_deliveryId`
WHERE `stock_deliveries`.`fk_stockID` = '189'
AND `delivery`.`delivery_completed` = '1'

SELECT SUM(stock_deliveries.stockValue) AS stockValues2
FROM `stock_deliveries`
LEFT JOIN `delivery` ON `delivery`.`pk_deliveryId`  = `stock_deliveries`.`fk_deliveryId`
WHERE `stock_deliveries`.`fk_stockID` = '189'
AND `delivery`.`delivery_completed` = '0

是否可以在单个查询中合并此2查询?提前谢谢。

4 个答案:

答案 0 :(得分:2)

是的,您在CASE WHEN等聚合函数中使用条件聚合(即SUM):

select
  sum(case when d.delivery_completed = 0 then sd.stockvalue end) as stockvalues0,
  sum(case when d.delivery_completed = 1 then sd.stockvalue end) as stockvalues1
from stock_deliveries sd
left join delivery d on d.pk_deliveryid = sd.fk_deliveryid
where sd.fk_stockid = 189;

答案 1 :(得分:1)

您可以在GROUP BY

的帮助下使用单个查询
SELECT SUM(stock_deliveries.stockValue) AS stockValues, `delivery`.`delivery_completed` as deliveryCompleted
FROM `stock_deliveries`
LEFT JOIN `delivery` ON `delivery`.`pk_deliveryId` =  `stock_deliveries`.`fk_deliveryId`
WHERE `stock_deliveries`.`fk_stockID` = '189'
GROUP BY `delivery`.`delivery_completed`;

这样做,delivery_completed的每个值都有一行与相关的总和(如果你只需要0和1值,你可以添加到where子句and delivery.delivery_completed IN (0,1))。 例如:

stockValues    deliveryCompleted
       1000           0
        700           1

答案 2 :(得分:0)

你可以使用"如果"内部总和,以检查您是否需要stockValues1stockValues0

中的值
SELECT SUM(IF(d.delivery_completed = 1, sd.stockValue, 0)) AS stockValues1, SUM(IF(d.delivery_completed = 0, sd.stockValue, 0)) AS stockValues2
FROM stock_deliveries sd
LEFT JOIN delivery d ON d.pk_deliveryId  = sd.fk_deliveryId
WHERE sd.fk_stockID = '189'
AND (d.delivery_completed = 1 OR d.delivery_completed = 0)

显然,如果" delivery_completed"只有1或0,您可以省略查询中的最后一个AND;)

编辑:正如Thorsten Kettner所说,你也可以使用case-when语法,只有一个" case"它们基本相同。在这种情况下,if语法更简洁,但如果您有更多选项更灵活,例如:

SELECT CASE sometable 
       WHEN 'top' THEN 'high' 
       WHEN 'center' THEN 'medium' 
       ELSE 'low' 
       END AS position

答案 3 :(得分:0)

您可以使用UNION ALL运算符来保留2个结果行的逻辑,但这些行现在是相同的结果,而不是2个分开的