计数行

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

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

  1. ----------------------
  2. ID | Date | Score
  3. ---------------------
  4. 345 | dt1 | 80
  5. 346 | dt1 | NULL
  6. 347 | dt1 | NULL
  7. 345 | dt1 | NULL
  8. 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条件中。。我从总分为空的行中减去这个。。但我的结果不正确。
第二种方法。

  1. SELECT id || date AS temp, count(*)
  2. FROM test_score
  3. WHERE score IS NULL AND id IS NOT NULL AND date IS NOT NULL
  4. AND pairs NOT IN
  5. (SELECT id || date AS temp
  6. FROM test_Score
  7. WHERE score IS NOT NULL AND id IS NOT NULL AND date IS NOT NULL)

有什么建议吗?

rpppsulh

rpppsulh1#

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

  1. select id, date
  2. from test_score
  3. group by id, date
  4. having max(score) is null;

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

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

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

展开查看全部
ztmd8pv5

ztmd8pv52#

一个简单的方法是:

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

另一种方法是:

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

相关问题