FAIRYFAR-INTERNAL
 
  FAIRYFAR-INTERNAL  |  SITEMAP  |  ABOUT-ME  |  HOME  
实现特殊功能的SQL案例

组合(复合,Composite Types)数据类型

PostgreSQL组合数据类型官方说明:

https://www.postgresql.org/docs/14/rowtypes.html

例子:

snippet.sql
test=# SELECT pg_stat_get_activity(NULL);
                                                   pg_stat_get_activity
--------------------------------------------------------------------------------------------------------------------------------
 (,4924,,"",,"",Activity,AutoVacuumMain,,,"2022-06-08 15:29:27.855337+08",,,,,,,"autovacuum launcher",f,,,,,,,,f,,f,1,0,UNKNOWN)
 (,4922,,"",,"",Activity,BgWriterMain,,,"2022-06-08 15:29:27.853938+08",,,,,,,"background writer",f,,,,,,,,f,,f,-1,0,UNKNOWN)
 (,4921,,"",,"",Activity,CheckpointerMain,,,"2022-06-08 15:29:27.852975+08",,,,,,,checkpointer,f,,,,,,,,f,,f,-1,0,UNKNOWN)
 (,4923,,"",,"",Activity,WalWriterMain,,,"2022-06-08 15:29:27.854843+08",,,,,,,walwriter,f,,,,,,,,f,,f,-1,0,UNKNOWN)
 (4 ROWS)

这个函数返回结果集是组合数据类型,下面是按需要提取相应的字段:

snippet.sql
test=# SELECT (x).pid, (x).backend_type FROM (SELECT pg_stat_get_activity(NULL) AS x) AS y;
 pid  |         backend_type
------+------------------------------
 4924 | autovacuum launcher
 4946 | logical replication launcher
 5086 | client backend
 4922 | background writer
 4921 | checkpointer
 4923 | walwriter
(6 ROWS)

选取每个分组中的第一条数据

准备测试数据:

snippet.sql
CREATE TABLE order_tab (name VARCHAR(32), create_time datetime, order_cnt INT);
INSERT INTO order_tab VALUES('张山','2022-06-01', 5);
INSERT INTO order_tab VALUES('张山','2022-05-01', 15);
INSERT INTO order_tab VALUES('张山','2022-05-06', 9);
 
INSERT INTO order_tab VALUES('李四','2022-06-02', 4);
INSERT INTO order_tab VALUES('李四','2022-01-22', 14);
INSERT INTO order_tab VALUES('李四','2022-01-24', 2);

选取每个name分组中的第一条数据:

snippet.sql
test=# SELECT * FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY name ORDER BY create_time DESC) AS rownum, name, order_cnt FROM order_tab
) T
WHERE T.rownum = 1;
 rownum | name | order_cnt
--------+------+-----------
      1 | 李四 |         4
      1 | 张山 |         5
(2 ROWS)


打赏作者以资鼓励: