Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 仅当所有分组行不为null时求和,否则返回null_Mysql - Fatal编程技术网

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

Mysql 仅当所有分组行不为null时求和,否则返回null,mysql,Mysql,我有一张这样的桌子: item_id quantity 1 2 1 3 2 NULL 2 4 3 NULL 3 NULL SELECT sum(`quantity`) AS `total_quantity`, FROM `items` GROUP BY `item_id` 现在我正在做这样的选择: item_id quantity 1 2 1

我有一张这样的桌子:

 item_id   quantity
 1         2
 1         3
 2         NULL
 2         4
 3         NULL
 3         NULL
SELECT 
   sum(`quantity`) AS `total_quantity`,
FROM `items`
GROUP BY `item_id`
现在我正在做这样的选择:

 item_id   quantity
 1         2
 1         3
 2         NULL
 2         4
 3         NULL
 3         NULL
SELECT 
   sum(`quantity`) AS `total_quantity`,
FROM `items`
GROUP BY `item_id`
现在,它分别返回5,4和NULL,但我想要5,NULL和NULL

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


谢谢

如果输出很奇怪,那么在大多数情况下,请求是将null替换为0或其他内容,不过这里有一种方法

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;

如果输出很奇怪,那么在大多数情况下,请求是将null替换为0或其他内容,不过这里有一种方法

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;

您只能使用
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的小提琴


您只能使用
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的小提琴


发布所提供数据集的预期输出,我只能实现不返回任何包含NULL的行。那可以接受吗?@thanyaj我已经有了,但我也需要那些台词。我需要找出一种方法来知道总和中的某些行是否为NULL。发布所提供数据集的预期输出我只能实现不返回任何包含NULL的行。那可以接受吗?@thanyaj我已经有了,但我也需要那些台词。我需要找出一种方法来知道总和中的某些行是否为空。像往常一样@M Khalid Junaid that是smart:-)这正是我需要的,它避免使用子查询。谢谢!:)像往常一样@M Khalid Junaid that是聪明的:-)这正是我需要的,它避免了使用子查询。谢谢!:)