多个日期行的按​​日期排序

Order By date for multiple date rows

我正在尝试编写一个 sql 查询来合并行,因此结果将如下所示:

post_id date_1 time_1 date_2 time_2
500 20220303 20:00:00
500 20220202 20:00:00

这是我到目前为止尝试过的方法:

SELECT 
    CASE meta_key WHEN"performance_date_1"THEN meta_value ELSE NULL END  AS date_1,
    CASE meta_key WHEN"performance_date_2"THEN meta_value ELSE NULL END  AS date_2
FROM test;

架构SQL:

CREATE TABLE test (
  meta_id bigint(20) AUTO_INCREMENT,
  post_id INT,
  meta_key varchar(255) NULL,
  meta_value longtext NULL,
  PRIMARY KEY (`meta_id`)
);
INSERT INTO test (post_id, meta_key, meta_value) VALUES (500, 'performance_date_1', '20220303');
INSERT INTO test (post_id, meta_key, meta_value) VALUES (500, 'performance_time_1', '20:00:00');
INSERT INTO test (post_id, meta_key, meta_value) VALUES (500, 'performance_date_2', '20220202');
INSERT INTO test (post_id, meta_key, meta_value) VALUES (500, 'performance_time_2', '20:00:00');

INSERT INTO test (post_id, meta_key, meta_value) VALUES (501, 'performance_date_1', '20220403');
INSERT INTO test (post_id, meta_key, meta_value) VALUES (501, 'performance_time_1', '20:00:00');
INSERT INTO test (post_id, meta_key, meta_value) VALUES (501, 'performance_date_2', '20220407');
INSERT INTO test (post_id, meta_key, meta_value) VALUES (501, 'performance_time_2', '19:00:00');

SQL Fiddle https://www.db-fiddle.com/f/9Zxq4HJpuAiSPvabQzL4ux/1

如有任何帮助,我们将不胜感激。

您想使用条件聚合:

SELECT
    post_id,
    MAX(CASE meta_key WHEN 'performance_date_1' THEN meta_value END) AS date_1,
    MAX(CASE meta_key WHEN 'performance_time_1' THEN meta_value END) AS time_1,
    MAX(CASE meta_key WHEN 'performance_date_2' THEN meta_value END) AS date_2,
    MAX(CASE meta_key WHEN 'performance_time_2' THEN meta_value END) AS time_2
FROM test
GROUP BY
    post_id;

感谢 Tim Biegeleisen 让我走上正轨。我最终使用了您的查询 作为子查询,然后 UNION ALL 我得到了我需要的结果。结果 table 看起来与我原来的问题略有不同,但对我有用。

查询SQL:

SELECT
    *
FROM 
  (SELECT
      post_id,
      MAX( CASE meta_key WHEN"performance_date_1"THEN meta_value ELSE NULL END ) AS new_date_1,
      MAX( CASE meta_key WHEN"performance_time_1"THEN meta_value ELSE NULL END ) AS new_time_1
  FROM test
  GROUP BY post_id
  UNION ALL
  SELECT
      post_id,
      MAX( CASE meta_key WHEN"performance_date_2"THEN meta_value ELSE NULL END ) AS new_date_1,
       MAX( CASE meta_key WHEN"performance_time_2"THEN meta_value ELSE NULL END ) AS new_time_1
  FROM test
  GROUP BY post_id) as T1
ORDER BY post_id

结果:

post_id new_date new_time
500 20220303 20:00:00
500 20220202 20:00:00
501 20220403 20:00:00
501 20220407 19:00:00

对于此示例数据,您可以将代码简化为:

SELECT post_id, 
       MAX(CASE WHEN SUBSTRING_INDEX(meta_key, '_', 2) = 'performance_date' THEN meta_value END) new_date_1,
       MAX(CASE WHEN SUBSTRING_INDEX(meta_key, '_', 2) = 'performance_time' THEN meta_value END) new_time_1
FROM test
GROUP BY post_id, SUBSTRING_INDEX(meta_key, '_', -1);

参见demo