根据序列和模式对列进行分类
Classify column on the basis of sequence and patterns
我在 Postgre 中有一列 Id
SQL table ABC
.
Id
是长度为 10 (minLength=maxLength=10)
的 bigint
我必须编写一个 SQL 查询并将 Id
分类为:
- 任何以恰好 3 个连续的奇数数字开始并以至少 2 个连续的偶数数字结束的 ID 被归类为“TYPE A”;
- 任何第二个数字大于6或第三个字符小于或等于4的ID都被归类为“TYPE B”;
- 任何奇数编号的 ID 都被归类为“TYPE C”,除非它以 7 结尾;
- 任何偶数编号的 Id 都被归类为“TYPE D”,除非它以 2 结尾;
- 所有其他 ID 都归类为“TYPE X”;
每种类型都可以用正则表达式找到。
create table ABC (
Id decimal(10) primary key check(length(Id::text)=10)
);
insert into ABC (Id) values
(1350000042)
, (1640000000)
, (1090000503)
, (1294567890)
, (1090000907)
, (1090000902)
/*
Type A: Any Id that commences with exactly 3 consecutive odd digits
and concludes with at least 2 consecutive even digits;
Type B: Any Id where the second digit is greater than 6
or the third character is less than or equal to 4;
Type C: Any odd-numbered Id unless it ends in 7;
Type D: Any even-numbered Id unless it ends in 2;
Type X: All other Id;
*/
select Id
, case
when Id::text ~ '^[13579]{3}[02468].*[02468]{2}$' then 'A'
when Id::text ~ '^(.[7-9]|..[0-4])' then 'B'
when Id::text ~ '[1359]$' then 'C'
when Id::text ~ '[0468]$' then 'D'
else 'X'
end as Type
from ABC
order by Type
id | type
---------: | :---
1350000042 | A
1760000000 | B
1640000000 | B
1090000503 | C
1294567890 | D
1090000907 | X
1090000902 | X
db<>fiddle here
我在 Postgre 中有一列 Id
SQL table ABC
.
Id
是长度为 10 (minLength=maxLength=10)
bigint
我必须编写一个 SQL 查询并将 Id
分类为:
- 任何以恰好 3 个连续的奇数数字开始并以至少 2 个连续的偶数数字结束的 ID 被归类为“TYPE A”;
- 任何第二个数字大于6或第三个字符小于或等于4的ID都被归类为“TYPE B”;
- 任何奇数编号的 ID 都被归类为“TYPE C”,除非它以 7 结尾;
- 任何偶数编号的 Id 都被归类为“TYPE D”,除非它以 2 结尾;
- 所有其他 ID 都归类为“TYPE X”;
每种类型都可以用正则表达式找到。
create table ABC ( Id decimal(10) primary key check(length(Id::text)=10) ); insert into ABC (Id) values (1350000042) , (1640000000) , (1090000503) , (1294567890) , (1090000907) , (1090000902)
/* Type A: Any Id that commences with exactly 3 consecutive odd digits and concludes with at least 2 consecutive even digits; Type B: Any Id where the second digit is greater than 6 or the third character is less than or equal to 4; Type C: Any odd-numbered Id unless it ends in 7; Type D: Any even-numbered Id unless it ends in 2; Type X: All other Id; */ select Id , case when Id::text ~ '^[13579]{3}[02468].*[02468]{2}$' then 'A' when Id::text ~ '^(.[7-9]|..[0-4])' then 'B' when Id::text ~ '[1359]$' then 'C' when Id::text ~ '[0468]$' then 'D' else 'X' end as Type from ABC order by Type
id | type ---------: | :--- 1350000042 | A 1760000000 | B 1640000000 | B 1090000503 | C 1294567890 | D 1090000907 | X 1090000902 | X
db<>fiddle here