我有一个查询,它会累计订单的总价值(每种产品的数量*价格总和)。我想要一个包含仅#" A"的总值的列。大小的产品。所以它应该总结所有产品的数量*价格,除了" C"尺寸产品。
只要我为每个产品返回一行,我就会得到预期的结果:每个A尺寸产品为5美元,C尺寸产品为0美元(在smallsize列中)。
SELECT
part_num, email, b.item, b.size_code,
IF(b.size_code IN ('A','B'), quan * price,0) AS smallsize,
quan * price AS price
FROM `orders` AS b
INNER JOIN `groups` AS a
ON b.ordnum = a.line_num
INNER JOIN `prices` AS c
ON c.item = b.item AND c.size_code = b.size_code
| part_num | email | item | size_code | smallsize | price |
|----------|--------------|------|-----------|-----------|-------|
| 2 | me@email.com | 7400 | A | 5 | 5 |
| 2 | me@email.com | 7400 | C | 0 | 20 |
| 2 | me@email.com | 7790 | A | 5 | 5 |
| 2 | me@email.com | 7870 | A | 5 | 5 |
| 2 | me@email.com | 7910 | A | 5 | 5 |
但是当我试图总结价格时,C尺寸产品包含在总数中($ 5 + $ 5 + $ 5 + $ 5 + $ 20 = $ 40)。
SELECT
part_num, email,
IF(b.size_code IN ('A','B'), sum(quan * price),0) AS smallsize,
sum(quan * price) AS price
FROM `orders` AS b
INNER JOIN `groups` AS a
ON b.ordnum = a.line_num
INNER JOIN `prices` AS c
ON c.item = b.item AND c.size_code = b.size_code;
| part_num | email | smallsize | price |
|----------|--------------|-----------|-------|
| 2 | me@email.com | 40 | 40 |
为什么第一个查询总共返回$ 20(如果你将smallsize列加起来),第二个查询返回$ 40为smallsize?
我创建了一个sqlfiddle来说明:http://sqlfiddle.com/#!9/b5ccd8/4
答案 0 :(得分:0)
您应该将IF
表达式放在SUM
内。否则你总结所有行,然后IF
决定是否在最终结果中显示总和或0
(这是不确定的,取决于它恰好选择哪一行b.size
。
SELECT
part_num, email,
sum(IF(b.size_code IN ('A','B'), quan * price,0)) AS smallsize,
sum(quan * price) AS price
FROM `orders` AS b
INNER JOIN `groups` AS a
ON b.ordnum = a.line_num
INNER JOIN `prices` AS c
ON c.item = b.item AND c.size_code = b.size_code;