如何使用 Postgresql 以另一种方式编写 select 查询以在 table 上显示数据?

How to write a select query for displaying data on a table in another way using Postgresql?

我想编写一个 select 查询来从 table 中选取数据,如下图所示,PICTURE_1 1.Table Containing Data 并像下面这张 link 中的这张图片一样显示它,PICTURE_2 2.Result of the query

关于数据:第一张图片显示了从具有 2 个子 ID (aa&bb) 的 3 个 ID(1,2&3) 登录到 table 2 秒的数据。图片中还显示了值和时间戳。 table 仅包含 3 列,如 PICTURE_1 所示。你们能帮我写一个查询来显示 table 中的数据,以便使用 Postgresql 显示如第二张图片所示吗?您可以使用 substring 函数提取 ID 名称。我使用的语言是 plpgsql。任何 ideas/logic 也将成为 good.Thank 你的时间。

请试试这个。这里行值已按列显示,也使用 CTE。

-- PostgreSQL(v11)
WITH cte_t AS (
     SELECT LEFT(name, 1) id
          , RIGHT(name, POSITION('.' IN REVERSE(name)) - 1) t_name
          , value
          , time_stamp
     FROM test
)
SELECT id
     , time_stamp :: DATE "date"
     , time_stamp :: TIME "time"
     , MAX(CASE WHEN t_name = 'aa' THEN value END) "aa"
     , MAX(CASE WHEN t_name = 'bb' THEN value END) "bb"
FROM cte_t
GROUP BY id, time_stamp
ORDER BY date, time, id;

请从urlhttps://dbfiddle.uk/?rdbms=postgres_11&fiddle=6d35047560b3f83e6c906584b23034e9

检查

检查此查询dbfiddle

with cte (name, value, timeStamp) as (values 
    ('1.aa', 1, '2021-08-20 10:10:01'),
    ('2.aa', 2, '2021-08-20 10:10:01'),
    ('3.aa', 3, '2021-08-20 10:10:01'),
    ('1.bb', 4, '2021-08-20 10:10:01'),
    ('2.bb', 5, '2021-08-20 10:10:01'),
    ('3.bb', 6, '2021-08-20 10:10:01'),
    ('1.aa', 7, '2021-08-20 10:10:02'),
    ('2.aa', 8, '2021-08-20 10:10:02'),
    ('3.aa', 9, '2021-08-20 10:10:02'),
    ('1.bb', 0, '2021-08-20 10:10:02'),
    ('2.bb', 1, '2021-08-20 10:10:02'),
    ('3.bb', 2, '2021-08-20 10:10:02')
), sub_cte as (
    select split_name[1] as id, split_name[2] as name, value, tt::date as date, tt::time as time from (
        select 
            regexp_split_to_array(name, '\.') split_name, 
            value, 
            to_timestamp(timestamp, 'YYYY-MM-DD HH:MI:SS') as tt 
        from cte
    ) foo
)
select id, date, time, a.value as aa, b.value as bb from sub_cte a
left join (
    select * from sub_cte where name = 'bb'
) as b using (id, date, time)
where a.name = 'aa'

结果

 id |    date    |   time   | aa | bb 
----+------------+----------+----+----
 1  | 2021-08-20 | 10:10:01 |  1 |  4
 2  | 2021-08-20 | 10:10:01 |  2 |  5
 3  | 2021-08-20 | 10:10:01 |  3 |  6
 1  | 2021-08-20 | 10:10:02 |  7 |  0
 2  | 2021-08-20 | 10:10:02 |  8 |  1
 3  | 2021-08-20 | 10:10:02 |  9 |  2
(6 rows)