我有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查询?提前谢谢。
答案 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)
你可以使用"如果"内部总和,以检查您是否需要stockValues1
或stockValues0
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个分开的