簡體   English   中英

使用 SQL 根據多個條件計算單個表中的行

[英]count rows from a single table based on multiple conditions using SQL

我正在努力實現看似簡單但我無法弄清楚的事情。 我有一張桌子,test_score..

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

該表可以有多個帶有 ID_Date 對的條目。例如,對於 ID 345 和 dt1,有兩個條目,一個帶有分數,另一個帶有 NULL 值。 我只想獲取那些具有 NULL 值的行。

在此示例中,返回 ID 為 346 和 347 的行。它必須是 ID_Date 對,並且這兩個都是 NON-NULL 值

My attempts so far: Select rows for which score is NULL, ID and date is not null INTERSECT select rows for which score is NOT NULL and ID and Date are NOT NULL. 這給了我一個行數,這些 id_date 對同時存在於 score_is_null 和 score_is_not_null 條件中。我從分數為 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)

有什么建議么?

如果您只想要這些對,請使用聚合:

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)上的索引。

一種簡單的方法是:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM