如何在DENSE_RANK()中不计算NULL值?

时间:2016-09-28 20:14:46

标签: sql google-bigquery

说我有下表:

col
NULL
1
1
2

然后我选择:

SELECT col, DENSE_RANK() OVER(ORDER BY col) as rnk from table

然后我得到:

col  rnk
NULL 1
1    2
1    2
2    3

我想得到的是:

col  rnk
NULL NULL
1    1
1    1
2    2

但如果我查询:

SELECT col, CASE WHEN col IS NOT NULL THEN DENSE_RANK() OVER(ORDER BY col) END as rnk from table

然后我得到:

col  rnk
NULL NULL
1    2
1    2
2    3

除了使用NULL子句之外,有没有办法在排名时忽略WHERE?我有一些其他列,其行不能省略。

2 个答案:

答案 0 :(得分:4)

使用partition by

SELECT col,
       (CASE WHEN col IS NOT NULL
             THEN DENSE_RANK() OVER (PARTITION BY (CASE WHEN col IS NOT NULL THEN 1 ELSE 2 END)
                                     ORDER BY col
                                    )
        END) as rnk
FROM table;

答案 1 :(得分:0)

以下是BigQuery Legacy SQL

SELECT col, CASE WHEN col IS NOT NULL THEN rnk END AS rnk
FROM (
  SELECT 
    col, (col IS NULL) AS tmp, 
    DENSE_RANK() OVER(PARTITION BY tmp ORDER BY col) AS rnk 
  FROM table
)