什么是超过一天卸货的订单,我有订单日期和卸货日期

时间:2017-02-21 16:06:43

标签: mysql sql database

我的职业生涯始于数据分析,我必须在日常工作中使用sql语句。我正在学习,但还需要提供一些快速的答案。所以我想我会在这个小组中提出一些问题。

我需要帮助才能编写sql查询来获取超过一天或两天(基于要求)的订单从该位置卸货。

活动类型列代表1,2,3,4

1-Order placed
2-Order discharged

日期记录在相应行的列日期

现在我想要求所有订单超过特定天数'n'

这是表格表格的示例。

活动表

|Order Nr|  activity|date|
|     1  |     1    | date1|    order placed
|     1  |     3    | date2|    order approved
|     1  |     4    | date3|    order packed
|     1  |     2    | date4|   order discharged

2 个答案:

答案 0 :(得分:1)

Not exists是一种方法:

select a.*
from activities a
where a.activity = 'placed' and
      not exists (select 1
                  from activities a2
                  where a2.activity = 'discharged' and
                        a2.ordernum = a.ordernum and
                        a2.date >= a.date and
                        a2.date <= a.date + interval 1 day
                 );

答案 1 :(得分:0)

您可以使用

获得订单展示位置
select * from activities where activity = 1

你可以猜到如何获得订单排放: - )

因此,将两者结合起来,只保留差异太大的行:

select p.order_nr, p.date as placed, d.date as discharged
from (select * from activities where activity = 1) p
join (select * from activities where activity = 2) d
  on d.order_nr = p.order_nr and datediff(d.date, p.date) > 1;

每个订单的汇总可以获得相同的结果:

select 
  order_nr, 
  any_value(case when activity = 2 then date end) as placed,
  any_value(case when activity = 1 then date end) as discharged
from activities
group by order_nr
having datediff(any_value(case when activity = 2 then date end), 
                any_value(case when activity = 1 then date end)) > 1;

如果您想要包含未结订单,您的工作方式几乎相同。对于没有已下达记录的订单,今天可能会输入此订单,因此昨天下达的订单可能仍然没有问题,而之前下达的订单已经打开太长时间。因此,如果没有dicharged记录我们想假装有一个date = today。

查询#1:

select p.order_nr, p.date as placed, d.date as discharged
from (select * from activities where activity = 1) p
left join (select * from activities where activity = 2) d
  on d.order_nr = p.order_nr and datediff(coalesce(d.date, curdate()), p.date) > 1;

查询#2:

select 
  order_nr, 
  any_value(case when activity = 2 then date end) as placed,
  any_value(case when activity = 1 then date end) as discharged
from activities
group by order_nr
having datediff(any_value(case when activity = 2 then date end), 
                coalesce(any_value(case when activity = 1 then date end), curdate())) > 1;