douyongwan5946 2017-05-02 06:39
浏览 32
已采纳

当同一个表中的其他列DO / DONT为NULL时,查找列的MIN / MAX

I have a few Postgres SELECT queries which is being pieced together according to form inputs via PHP. One of these is a SELECT query which looks to retrieve the min value within each field (I also have one which finds max).

e.g. for the min values:

SELECT
  MIN(col1) "Min_col1"
  MIN(col2) "Min_col2"
  MIN(col3) "Min_col3"
FROM table

Unfortunately, I have quite a lot of NULL values in the table, spread over all fields. To cope with this, I have added check boxes to the form which allows the user to select whether NULL values should be included/excluded as part of this query.

For example, if the user wanted to include NULL values for all columns:

SELECT
  MIN(col1) "Min_col1"
  MIN(col2) "Min_col2"
  MIN(col3) "Min_col3"
FROM table
WHERE
  (col1 IS NULL) AND
  (col2 IS NULL) AND
  (col3 IS NULL)

However, since each of the fields have at least one NULL value, the above query would return all NULLS.

What I would instead like is to be able to retrieve the MIN for each field, while either including/excluding NULL values for the other fields. e.g. MIN(col1) while either including/excluding NULLS for col2, col2 & col3 etc.

Whats the easiest way to go about this? Keep in mind that the query is being put together from form inputs via PHP, so would like to keep it as modular as possible...

  • 写回答

2条回答 默认 最新

  • dongzhuo2371 2017-05-02 07:06
    关注

    for query below if null_only::boolean is false, returns min, else null:

    SELECT
        case when not null_only then  MIN(col1) else null end "Min_col1"
      , case when not null_only then  MIN(col2) else null end "Min_col2"
      , case when not null_only then  MIN(col3) else null end "Min_col3"
    FROM table
    WHERE
      (col1 IS NULL) AND
      (col2 IS NULL) AND
      (col3 IS NULL)
    

    here's working example for prepared statement:

    t=# prepare q1 (boolean) as select case when not $1 then  MIN(oid) else null end col1 from pg_class;
    PREPARE
    Time: 10.905 ms
    t=# execute q1(true);
     col1
    ------
    
    (1 row)
    
    Time: 6.216 ms
    t=# execute q1(false);
     col1
    ------
      112
    (1 row)
    
    Time: 7.169 ms
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog