按日期排序是不是有效?

时间:2018-03-05 22:51:28

标签: sql-order-by

我有以下表格:

 CREATE TABLE logins (
  type_id BIGINT NOT NULL,
  created_date TIMESTAMP(0) WITHOUT TIME ZONE DEFAULT now() NOT NULL);


  INSERT INTO logins VALUES 
  (5,   '1/26/2018 5:00:00 PM'),
  (5    ,'1/26/2018 3:45:44 PM'),
  (5,   '1/26/2018 3:45:44 PM')

当我单独运行此代码时:

SELECT l.type_id , l.created_date  FROM logins l 
WHERE  
          l.type_id = 5 AND
          l.created_date BETWEEN ((CAST('1/26/2018' AS DATE) - 1) + TIME ' 17:00:00') AND
          (CAST('1/26/2018' AS DATE) + TIME ' 17:00:00')

          ORDER BY l.created_date DESC

它以我想要的方式命令日期,但是当我运行以下代码时:

WITH results as (SELECT l.type_id , l.created_date  FROM logins l 
WHERE  
          l.type_id = 5 AND
          l.created_date BETWEEN ((CAST('1/26/2018' AS DATE) - 1) + TIME ' 17:00:00') AND
          (CAST('1/26/2018' AS DATE) + TIME ' 17:00:00')

          ORDER BY l.created_date DESC)

SELECT * FROM results 
UNION 
SELECT 0, NULL 
WHERE NOT EXISTS (SELECT * FROM results )

订单根本不起作用。我想知道原因。

1 个答案:

答案 0 :(得分:1)

将命令放在sql的末尾。此外,UNION删除重复项,而UNION ALL不删除重复项。试试这个,你会得到与以前相同的结果。感谢。

WITH results as (SELECT l.type_id , l.created_date  FROM logins l 
WHERE  
          l.type_id = 5 AND
          l.created_date BETWEEN ((CAST('1/26/2018' AS DATE) - 1) + TIME ' 17:00:00') AND
          (CAST('1/26/2018' AS DATE) + TIME ' 17:00:00')
          )
SELECT * FROM results 
UNION
SELECT 0, NULL 
WHERE NOT EXISTS (SELECT * FROM results )
ORDER BY created_date DESC