我有这个查询:
SELECT
`t2`.`upc`,
FORMAT(SUM(`t2`.`qty`), 0) AS <COLUMN NAME>
FROM
(`orders` `t1`
JOIN `sales` `t2` ON ((`t2`.`order_id` = `t1`.`id`)))
WHERE <CONDITION>
GROUP BY `t2`.`upc`
与以下CONDITIONS
配合使用的情况:
t1.`date_placed` > (CURDATE() - INTERVAL 42 DAY)
t1.order_status = 1
我试图合并这些单独的查询,如果不满足条件,则将其对应列的结果设为0。
这是我的尝试
SELECT
`t2`.`upc`,
CASE
WHEN (`t1`.`date_placed` > (CURDATE() - INTERVAL 42 DAY))
THEN FORMAT(SUM(`t2`.`qty`), 0)
ELSE 0
END AS `qty_sold`,
CASE
WHEN t1.order_status = 1
THEN FORMAT(SUM(`t2`.`qty`, 0))
ELSE 0
END AS `order_qty`
FROM
`orders` `t1`
JOIN `sales` `t2` ON (`t2`.`order_id` = `t1`.`id`)
WHERE `upc`=1001 OR `upc`=1002 OR `upc`=1003
GROUP BY `t2`.`upc`;
订单表:
+-----------+--------------+------------+
| id | date_placed |order_status|
+-----------+--------------+------------+
| 1 | 2019-02-22 | 1 |
+-----------+--------------+------------+
| 2 | 2019-02-22 | 1 |
+-----------+--------------+------------+
| 3 | 2018-02-22 | 2 |
+-----------+--------------+------------+
销售表:
+-----------+--------------+------+-----+
| id | order_id | upc | qty |
+-----------+--------------+------+-----+
| 1 | 1 | 1001 | 1 |
+-----------+--------------+------+-----+
| 2 | 1 | 1002 | 1 |
+-----------+--------------+------+-----+
| 3 | 1 | 1003 | 1 |
+-----------+--------------+------+-----+
| 4 | 2 | 1001 | 3 |
+-----------+--------------+------+-----+
| 5 | 3 | 1001 | 2 |
+-----------+--------------+------+-----+
| 6 | 3 | 1002 | 1 |
+-----------+--------------+------+-----+
预期结果:
+-----------+--------------+------------+
| upc | qty_sold | order_qty |
+-----------+--------------+------------+
| 1001 | 4 | 4 |
+-----------+--------------+------------+
| 1002 | 1 | 1 |
+-----------+--------------+------------+
| 1003 | 1 | 1 |
+-----------+--------------+------------+
我在做什么错?如果无法尝试使用CASE
语句,是否有另一种方式组合这些查询?
任何建议将不胜感激:)
答案 0 :(得分:1)
case
应该是聚合函数的参数:
FORMAT(SUM(CASE WHEN (`t1`.`date_placed` > (CURDATE() - INTERVAL 42 DAY)) THEN `t2`.`qty`ELSE 0
END), 0) AS `qty_sold`,
FORMAT(SUM(CASE WHEN t1.order_status = 2 THEN t2`.`qty` ELSE 0
END), 0) `order_qty`
答案 1 :(得分:1)
在案例表达式之前使用总和,并使用in
SELECT
`t2`.`upc`,
sum(CASE
WHEN (`t1`.`date_placed` > (CURDATE() - INTERVAL 42 DAY))
THEN FORMAT((`t2`.`qty`), 0)
ELSE 0
END ) AS `qty_sold`,
sum(CASE
WHEN t1.order_status = 2
THEN FORMAT((`t2`.`qty`, 0))
ELSE 0
END) AS `order_qty`
FROM
`orders` `t1`
JOIN `sales` `t2` ON (`t2`.`order_id` = `t1`.`id`)
WHERE t2.upc in (1001,1002,1003)
GROUP BY `t2`.`upc`;