仅当所有分组行不为null时才求和,否则返回null

时间:2015-07-03 18:59:29

标签: mysql

我有一张这样的表:

 item_id   quantity
 1         2
 1         3
 2         NULL
 2         4
 3         NULL
 3         NULL

现在我正在做这样的SELECT:

SELECT 
   sum(`quantity`) AS `total_quantity`,
FROM `items`
GROUP BY `item_id`

现在,它分别返回5,4和NULL,但我想要5,NULL和NULL。

我希望如果分组行中有NULL值,则总和应为NULL,而不是列不为空的行的总和。我怎样才能做到这一点?

谢谢!

3 个答案:

答案 0 :(得分:2)

如果有奇怪的输出,多数情况下,请求是用0或其他东西替换null,但这是一种方法

select 
x.item_id,
max(x.quantity) as quantity from (
  SELECT 
  t1.item_id,
  @sm:= if(@prev_item = item_id, @sm_qty+quantity,quantity) as quantity,
  @prev_item :=item_id,
  @sm_qty:= quantity
  from items t1,(select @prev_item:=null,@sm_qty=0)x
  order by item_id
)x
group by x.item_id;

http://www.sqlfiddle.com/#!9/ccb36/13

答案 1 :(得分:2)

您只能使用case语句检查某个组中的任何行是否包含null作为数量

SELECT item_id,
     CASE WHEN SUM(quantity IS NULL) > 0 
     THEN NULL 
     ELSE SUM(quantity) 
     END quantity
FROM items
GROUP BY item_id

使用@Abhik Chakraborty的小提琴

DEMO

答案 2 :(得分:0)

SELECT * FROM (
    ( -- Get all not null quantities
        SELECT 
           `i1`.`item_id`,
           sum(`i1`.`quantity`) AS `total_quantity`
           FROM `items` AS `i1`
           WHERE `i1`.`item_id` NOT IN ( SELECT `i2`.`item_id` FROM `items` AS `i2` WHERE `i2`.`quantity` IS NULL )
        GROUP BY `item_id`
    )
    UNION ALL
    ( -- Get all null quantities
        SELECT 
           `i3`.`item_id`,
           null AS `i3`.`total_quantity`
           FROM `items` AS `i3`
           WHERE `i3`.`item_id` IN ( SELECT `i4`.`item_id` FROM `items` AS `i4` WHERE `i4`.`quantity` IS NULL )
        GROUP BY `i3.item_id`
    )
) AS items_table
ORDER BY items_table.item_id
相关问题