gpt4 book ai didi

Postgresql 排序 string_agg

转载 作者:行者123 更新时间:2023-11-29 14:20:00 45 4
gpt4 key购买 nike

我运行以下查询 string_agg(DISTINCT grades, '|'),它按 01|02|03|04|05|KG|PK 的顺序执行并输出我的结果

如何以这种方式重新排列 PK|KG|01|02|03|04|05

SELECT
U.CUSTOM_100000001 AS USERID
, SC.TITLE
, U.FIRST_NAME
, U.LAST_NAME
, string_AGG(DISTINCT SGL.short_name, '|')
FROM
USERS U
, COURSE_PERIODS CP
, SCHOOLS SC
, school_gradelevels SGL
WHERE
CP.SCHOOL_ID=SC.ID
AND
U.STAFF_ID = CP.TEACHER_ID
AND
SGL.SCHOOL_ID = SC.ID
AND
CP.SYEAR =2015
AND
SGL.short_name in('PK','KG','01','02','03','04','05','06','07','08')
AND
SC.CUSTOM_327 IN ('0021','0025','0051','0061','0071','0073','0081','0101','0111','0131','0211','0‌​221','0294','0301','0321','0341','0361','0371','0291')
GROUP BY
U.CUSTOM_100000001, SC.TITLE, U.FIRST_NAME, U.LAST_NAME

最佳答案

在 PostgreSQL 9.0+ 中是可能的:

SELECT
string_agg(DISTINCT SGL.short_name
, '|' ORDER BY
(substring(SGL.short_name, '^[0-9]+'))::int NULLS FIRST,
substring(SGL.short_name, '[^0-9_]+$') DESC)
FROM school_gradelevels SGL;

测试示例:

WITH tbl(grade) AS (
VALUES
('01'),
('02'),
('03'),
('PK'),
('KG')
)
SELECT grade
FROM tbl
ORDER BY (substring(grade, '^[0-9]+'))::int NULLS FIRST, substring(grade, '[^0-9_]+$') DESC;

结果:

 grade
-------
PK
KG
01
02
03
(5 rows)

Aggregate Expressions

关于Postgresql 排序 string_agg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32143271/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com