這是我正在使用的表的示例。我想要實作的是選擇型別不是“NONE”的最新行,除非“NONE”是該 ID 唯一可用的型別。
| ID | 日期 | 型別 |
|---|---|---|
| 123 | 01-01-2021 | 沒有任何 |
| 123 | 12-31-2021 | 沒有任何 |
| 123 | 01-01-2021 | 金屬 |
| 123 | 12-31-2021 | 金屬 |
從上面的示例表中,我希望查詢回傳這個
| ID | 日期 | 型別 |
|---|---|---|
| 123 | 12-31-2021 | 金屬 |
如果該表僅包含“NONE”型別,例如此示例...
| ID | 日期 | 型別 |
|---|---|---|
| 123 | 01-01-2021 | 沒有任何 |
| 123 | 12-31-2021 | 沒有任何 |
| 123 | 01-01-2021 | 沒有任何 |
| 123 | 12-31-2021 | 沒有任何 |
然后我希望結果集是..
| ID | 日期 | 型別 |
|---|---|---|
| 123 | 12-31-2021 | 沒有任何 |
我已經嘗試了很多不同的方法來做到這一點,但我目前的嘗試看起來像這樣。它在表中只有一個 ID 時有效,但不適用于我嘗試為表中的每個特定 ID 選擇一行時。
SELECT DISTINCT ON (id),
date,
type
FROM
example_table
WHERE
CASE
WHEN
( SELECT
COUNT(*)
FROM
example_table t
WHERE
t.type <> 'NONE'
AND t.id = example_table.id)
<> 0
THEN type <> 'NONE'
ELSE 1=1
END
ORDER BY
id, date DESC
uj5u.com熱心網友回復:
您可以將 Row_number() 函式與 case 陳述句一起使用來確定要選擇的行。
with cte AS
(
select id,
date,
type,
row_number() over(partition by id
order by case when type <> 'NONE' THEN 1 ELSE 2 END, date desc
) as RN
from test
)
select *
from cte
where rn = 1
SQL小提琴
uj5u.com熱心網友回復:
不使用分析函式:SQL:
with cte
as
(
select id,type,flag, max(date) date from (select id , date , type, case when type='NONE' then 'flag_none' else 'flag_not_none' end as flag from test) x group by id,type,flag)
select id,type,date from cte where flag='flag_not_none' and (id,date) in (select id,max(date) from cte group by id)
union
select id,type,date from cte where id not in (select id from cte where flag='flag_not_none' and (id,date) in (select id,max(date) from cte group by id)) and flag='flag_none';
完全執行:
CREATE TABLE test
(
id int,
date date,
type text
);
insert into test
values
(123, '01-01-2021', 'NONE'),
(123, '12-31-2021', 'NONE'),
(123, '01-01-2021', 'METAL'),
(123, '12-31-2021', 'PLASTIC'),
(124, '01-01-2021', 'NONE'),
(124, '12-31-2021', 'NONE'),
(124, '01-01-2021', 'NONE'),
(124, '12-31-2021', 'NONE'),
(125, '12-25-2021', 'NONE'),
(125, '12-25-2021', 'RUBBER'),
(125, '12-31-2021', 'STEEL');
postgres=# with cte
postgres-# as
postgres-# (
postgres(# select id,type,flag, max(date) date from (select id , date , type, case when type='NONE' then 'flag_none' else 'flag_not_none' end as flag from test) x group by id,type,flag)
postgres-# select id,type,date from cte where flag='flag_not_none' and (id,date) in (select id,max(date) from cte group by id)
postgres-# union
postgres-# select id,type,date from cte where id not in (select id from cte where flag='flag_not_none' and (id,date) in (select id,max(date) from cte group by id)) and flag='flag_none';
id | type | date
----- --------- ------------
123 | PLASTIC | 2021-12-31
124 | NONE | 2021-12-31
125 | STEEL | 2021-12-31
(3 rows)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/391462.html
標籤:sql 数据库 PostgreSQL的
