【问题标题】:Combine Date and Time Fields and Order By DateTime Field合并日期和时间字段并按日期时间字段排序
【发布时间】:2022-01-29 19:00:46
【问题描述】:

我想合并元值 performance_date_1performance_time_1 的日期和时间,然后按这个新的 DATETIME 值排序。到目前为止,这是我的 SQL 查询,但没有运气。

查询 SQL:

SELECT TIMESTAMP(performance_date_1, performance_time_1) as DateTimeTS FROM test ORDER BY DateTimeTS;

由于表格的结构,我很难做到这一点。我不确定表格是否需要先旋转 GROUP BY post_id 列。

架构 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', '20220405');
INSERT INTO test (post_id, meta_key, meta_value) VALUES (500, 'performance_time_1', '21:00:00');
INSERT INTO test (post_id, meta_key, meta_value) VALUES (500, 'performance_date_2', '20220407');
INSERT INTO test (post_id, meta_key, meta_value) VALUES (500, 'performance_time_2', '22: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 小提琴 https://www.db-fiddle.com/f/rSwxZKvBQ2JiwW5H6KawoW/1

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    你是对的。你应该做一个数据透视表。

    SELECT
        post_id,
        MAX( CASE meta_key WHEN"performance_date_1"THEN meta_value ELSE NULL END ) AS date_1,
        MAX( CASE meta_key WHEN"performance_time_1"THEN meta_value ELSE NULL END ) AS time_1,
        MAX( CASE meta_key WHEN"performance_date_2"THEN meta_value ELSE NULL END ) AS date_2,
        MAX( CASE meta_key WHEN"performance_time_2"THEN meta_value ELSE NULL END ) AS time_2,
        TIMESTAMP(
            MAX( CASE meta_key WHEN"performance_date_1"THEN meta_value ELSE NULL END ),
            MAX( CASE meta_key WHEN"performance_time_1"THEN meta_value ELSE NULL END )
        ) AS datetime_1,
        TIMESTAMP(
            MAX( CASE meta_key WHEN"performance_date_2"THEN meta_value ELSE NULL END ),
            MAX( CASE meta_key WHEN"performance_time_2"THEN meta_value ELSE NULL END )
        ) AS datetime_2
    FROM
        test
    GROUP BY
        post_id
    ORDER BY
        datetime_1;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      相关资源
      最近更新 更多