SQL订单由2个日期列组成

时间:2012-05-08 21:14:44

标签: sql

我有一张订单表。每个订单都有delivery_datecollection_date

我希望将订单检索为一周的时间表,以显示接下来要做的事情。

所以我想我想要显示时间序列,以便星期三的收集出现在星期二的交货和周四的另一次交货之间。

有关如何使用SQL执行此操作的任何想法吗?

2 个答案:

答案 0 :(得分:8)

使用Union ALL,我将您的每个订单记录视为两个记录:一个用于交付,一个用于集合。如果您有另一个日期(修复?),您将使用类似字段合并另一个子查询。

由于您未在订单表中提供任何规格,因此我编写了很多这些内容。

select *
from (
   Select OrderID
       , 'Colection' as VisitType
      , Collection_Date as VisitDate
   from Orders
   Union All
   Select OrderID
     , 'Delivery' as VisitType
     , Delivery_Date as VisitDate
  from Orders
) as v
order by v.VisitDate

答案 1 :(得分:3)

根据您使用的数据库,它将与

类似
ORDER BY CASE WHEN delivery_date > collection_date 
         THEN collection_date ELSE delivery_date END
相关问题