我有两个查询,用于根据标志值获取值之和
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条答案
按热度按时间taor4pac1#
您可以在sum中使用“if”来检查是否需要中的值
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)
SELECT CASE sometable
WHEN 'top' THEN 'high'
WHEN 'center' THEN 'medium'
ELSE 'low'
END AS position
t3psigkw2#
是的,您将使用条件聚合(即。
CASE WHEN
在聚合函数中,例如SUM
):jyztefdp3#
您可以在groupby的帮助下使用单个查询
这样,您将为的每个值都有一行
delivery_completed
使用关联的sum(如果只需要0和1的值,可以添加到where子句中)and delivery.delivery_completed IN (0,1)
). 例子:hsgswve44#
你可以用
UNION ALL
运算符来保持两个结果行的逻辑,但它们现在位于相同的结果中,而不是两个分开的结果行