计数行

qkf9rpyu  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(285)

我正在努力实现看似简单的目标,但我想不通。我有一张table,考试成绩。。

----------------------
ID   | Date | Score
---------------------
345 | dt1  | 80
346 | dt1  | NULL
347 | dt1  | NULL
345 | dt1  | NULL
348 | dt2  | 75

该表可以有多个id\u date对的条目。。例如,对于id345和dt1,有两个条目,一个带有分数,另一个为空值。我想获取那些只有空值的行。
在本例中,返回ID为346和347的行。。它必须是一个id\u日期对,并且这两个都是非空值
我迄今为止的尝试:选择score为null、id和date不为null的行相交选择score为null、id和date不为null的行。这给了我一个行的计数,其中这些id\u日期对同时存在于score\u is\u null和score\u is\u not\u null条件中。。我从总分为空的行中减去这个。。但我的结果不正确。
第二种方法。

SELECT id || date AS temp, count(*)
FROM test_score
WHERE score IS NULL AND id IS NOT NULL AND date IS NOT NULL
AND pairs NOT IN 
(SELECT id || date AS temp
FROM test_Score 
WHERE score IS NOT NULL AND id IS NOT NULL AND date IS NOT NULL)

有什么建议吗?

rpppsulh

rpppsulh1#

如果只需要对,则使用聚合:

select id, date
from test_score
group by id, date
having max(score) is null;

如果出于某种原因确实需要原始行,请使用 not exists :

select ts.*
from test_score ts
where not exists (select 1
                  from test_score ts2
                  where ts2.id = ts.id and ts2.date = ts.date and ts2.score is not null
                 );

为了提高性能,您需要一个索引 (id, date, score) .

ztmd8pv5

ztmd8pv52#

一个简单的方法是:

Select ids, dt, score from (Select t.*, max(score) OVER (PARTITION BY ids, dt) mx from tab1 t)
where mx IS NULL

另一种方法是:

Select ids, dt, score from (Select t.*, count(ids) OVER (PARTITION BY ids, dt) mx from tab1 t)
where mx = 1 and score is NULL;

相关问题