当麻木为空时,MySQL CASE忽略麻木为非空的记录

时间:2019-03-06 12:04:32

标签: mysql group-by max min

我在表中有这些数据:

numb    m   value
8070    1   7.63
NULL    1   7.64
NULL    1   7.65
8070    2   7.939
8070    2   7.935
8070    2   7.941
NULL    3   7.62
8070    4   7.92
8070    4   7.935

每个MIN(value)我需要MAX(value)m,如果有一个value没有numb(NULL),则 numb一起使用。

所以我应该得到以下结果:

numb    m   value
NULL    1   7.64
NULL    1   7.65
8070    2   7.935
8070    2   7.941
NULL    3   7.62
8070    4   7.92
8070    4   7.935

我已经尝试了很多不同的方法,但是似乎没有任何效果,而且我不知道如何查找相关信息。你能给我指出正确的方向吗?

更新: 获取值的数量,看起来像这样:

COALESCE(
IF(
  COUNT(
    CASE
      WHEN m IN (2, 4)
      THEN value
      ELSE
      CASE
        WHEN m IN (1, 3) AND numb IS NULL
        THEN value
      END
    END
  ) = 0,
  NULL,
  COUNT(
    CASE
      WHEN m IN (2, 4)
      THEN value
      ELSE
      CASE
        WHEN m IN (1, 3) AND numb IS NULL
        THEN value
      END
    END
  )
),
COUNT(
  CASE
    WHEN m IN (1, 3)
    AND numb IS NOT NULL
    THEN value
  END
)
) AS cnt

1 个答案:

答案 0 :(得分:1)

此查询应为您提供所需的结果。它具有两层嵌套的派生表。第一个:

SELECT m,
       MIN(CASE WHEN numb IS NULL THEN value END) AS min_null,
       MAX(CASE WHEN numb IS NULL THEN value END) AS max_null,
       MIN(CASE WHEN numb IS NOT NULL THEN value END) AS min_normal,
       MAX(CASE WHEN numb IS NOT NULL THEN value END) AS max_normal
FROM numbers
GROUP BY m;

根据m是数字还是numb来计算NULL的每个值的最小值和最大值。在下一级别,

SELECT m,
       COALESCE(min_null, min_normal) AS min_value,
       COALESCE(max_null, max_normal) AS max_value
FROM (... query 1...)

我们使用计算要使用的适当的最小值和最大值(如果存在NULL值,则使用该值,否则使用与数值numb关联的值)。最后,我们将数字表JOIN移至查询2的结果,以为numb的每个值找到合适的m值:

SELECT n.numb, n.m, n.value
FROM numbers n
JOIN (... query 2 ...) num ON num.m = n.m AND (num.min_value = n.value OR num.max_value = n.value)
ORDER BY n.m, n.value

输出:

numb    m   value
null    1   7.64
null    1   7.65
8070    2   7.935
8070    2   7.941
null    3   7.62
8070    4   7.92
8070    4   7.935

Demo on dbfiddle

完整查询:

SELECT n.numb, n.m, n.value
FROM numbers n
JOIN (SELECT m,
             COALESCE(min_null, min_normal) AS min_value,
             COALESCE(max_null, max_normal) AS max_value
      FROM (SELECT m,
                   MIN(CASE WHEN numb IS NULL THEN value END) AS min_null,
                   MAX(CASE WHEN numb IS NULL THEN value END) AS max_null,
                   MIN(CASE WHEN numb IS NOT NULL THEN value END) AS min_normal,
                   MAX(CASE WHEN numb IS NOT NULL THEN value END) AS max_normal
            FROM numbers
            GROUP BY m) n) num ON num.m = n.m AND (num.min_value = n.value OR num.max_value = n.value)
ORDER BY n.m, n.value