Oracle:Analytic Function分区为可空值

时间:2012-03-07 16:28:48

标签: oracle

我不想计算NULL值。因为NULL不应该等于NULL。

查看此查询结果:link

WITH temp as (
SELECT 'A' as master , 1 Col from dual
UNION SELECT 'A' , 3  from dual
UNION SELECT 'B' , 1 from dual
UNION SELECT 'B' , 2 from dual
UNION SELECT 'C' , 1 from dual
UNION SELECT NULL , 1 from dual
UNION SELECT NULL , 2 from dual)
SELECT
   master,
   count(Col) over (partition by master)
FROM
  temp

3 个答案:

答案 0 :(得分:4)

或者,过滤掉它们:

  1  WITH temp as (
  2  SELECT 'A' as master , 1 Col from dual
  3  UNION SELECT 'A' , 3  from dual
  4  UNION SELECT 'B' , 1 from dual
  5  UNION SELECT 'B' , 2 from dual
  6  UNION SELECT 'C' , 1 from dual
  7  UNION SELECT NULL , 1 from dual
  8  UNION SELECT NULL , 2 from dual)
  9  SELECT
 10     master,
 11     count(Col) over (partition by master)
 12  FROM
 13    temp
 14* WHERE master is not null
SQL> /

M COUNT(COL)OVER(PARTITIONBYMASTER)
- ---------------------------------
A                                 2
A                                 2
B                                 2
B                                 2
C                                 1

答案 1 :(得分:3)

如果您不想过滤掉master IS NULL的行,您可以执行类似

的操作

SELECT master,        SUM(主时IS NULL的情况)                  那么0                  ELSE 1              结束)(主人分区)   从临时

SQL> ed
Wrote file afiedt.buf

  1  WITH temp as (
  2  SELECT 'A' as master , 1 Col from dual
  3  UNION SELECT 'A' , 3  from dual
  4  UNION SELECT 'B' , 1 from dual
  5  UNION SELECT 'B' , 2 from dual
  6  UNION SELECT 'C' , 1 from dual
  7  UNION SELECT NULL , 1 from dual
  8  UNION SELECT NULL , 2 from dual)
  9  SELECT master,
 10         SUM( CASE WHEN master IS NULL
 11                   THEN 0
 12                   ELSE 1
 13               END) OVER (PARTITION BY master)
 14*   FROM temp
SQL> /

M SUM(CASEWHENMASTERISNULLTHEN0ELSE1END)OVER(PARTITIONBYMASTER)
- -------------------------------------------------------------
A                                                             2
A                                                             2
B                                                             2
B                                                             2
C                                                             1
                                                              0
                                                              0

答案 2 :(得分:3)

Null 等于为null。但是从聚合的角度来看,null 等价为null。分析不是那样做的;这是聚合本身。

  1  WITH temp as (
  2  SELECT 'A' as master , 1 Col from dual
  3  UNION SELECT 'A' , 3 from dual
  4  UNION SELECT 'B' , 1 from dual
  5  UNION SELECT 'B' , 2 from dual
  6  UNION SELECT 'C' , 1 from dual
  7  UNION SELECT NULL , 1 from dual
  8  UNION SELECT NULL , 2  from dual )
  9  SELECT
 10     master,
 11     count(Col)
 12  FROM
 13*   temp group by master
SQL> /

M COUNT(COL)
- ----------
           2
A          2
B          2
C          1