如何获取两个日期戳之间的时差并按降序排列

时间:2019-06-10 05:42:01

标签: sql redash

我需要两个日期戳之间的时差(以小时为单位),并且需要按降序排列以获取中位数

SELECT "fulfillmentshistories"."fulfillmentid" as "Fulfillment ID" FROM FULFILLMENTHISTORIES
WHERE (Fulfillments."status" IN ('paid','delivered') AND (DATE("fulfillmenthistories"."createdAt") BETWEEN DATE('{{startDate}}') AND DATE('{{endDate}}')))
union
SELECT DATEDIFF(HOUR,   'startDate'-'endDate') as DATEDIFF;
ORDER BY DATEDIFF, DESC

这是我尝试过的,请帮助

SELECT "fulfillmentshistories"."fulfillmentid" as "Fulfillment ID" FROM    FULFILLMENTHISTORIES
WHERE (Fulfillments."status" IN ('paid','delivered') AND (DATE ("fulfillmenthistories"."createdAt") BETWEEN DATE('{{startDate}}') AND DATE('{{endDate}}')))
union
SELECT DATEDIFF(HOUR,   'startDate'-'endDate') as DATEDIFF;
ORDER BY DATEDIFF, DESC
  

运行查询时出错:“ ORDER”第5行或附近的语法错误:ORDER BY DATEDIFF,DESC ^

2 个答案:

答案 0 :(得分:0)

SELECT DATEDIFF(HOUR, 'startDate'-'endDate') as DATEDIFF; ORDER BY DATEDIFF, DESC

应该是

SELECT DATEDIFF(HOUR, 'startDate'-'endDate') as DATEDIFF ORDER BY DATEDIFF, DESC ;

并尝试避免使用类似于函数名的别名。

答案 1 :(得分:0)

UNION
SELECT DATEDIFF(HOUR,   'startDate'-'endDate') as DATEDIFF;
ORDER BY DATEDIFF, DESC

应该是

UNION
SELECT DATEDIFF(HOUR,   'startDate'-'endDate') as DATEDIFF
ORDER BY DATEDIFF DESC;

删除DATEDIFF之后的分号和ORDER BY DATEDIFF之后的逗号。分号应该出现在SQL语句的末尾,因为整个语句是一个sql语句。