sql – 如何按特定顺序选择(几乎)唯一值

前端之家收集整理的这篇文章主要介绍了sql – 如何按特定顺序选择(几乎)唯一值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在一次旅行中,按照特定的顺序有几个停靠点(停止=加载或交付一个或多个订单的地址).
例如:
  1. Trip A
  2. Trip_order Action Place Ordernumber
  3. 10 Load Paris 394798
  4. 20 Load Milan 657748
  5. 30 UnLoad Athens 657748
  6. 40 Unload Thessaloniki 394798
  7. 50 Load Thessaloniki 10142
  8. 60 Load Thessaloniki 6577
  9. 70 Unload Athens 6577
  10. 80 Unload Athens 10412
  11. 90 Load Thessaloniki 975147
  12. 100 Unload Paris 975147

我希望按行程顺序查看具体的停靠点:

  1. Load Paris
  2. Load Milan
  3. Unload Athens
  4. Unload Thessaloniki
  5. Load Thessaloniki
  6. Unload Athens
  7. Load Thessaloniki
  8. Unload Paris

我确实看过This,但如果我这样做,我只能卸载雅典,卸载塞萨洛尼基并加载塞萨洛尼基一次.

我该如何解决这个问题?

编辑:11:11(UTC 01:00)
更具体地说:这些是提供此信息的表格:

  1. Trips
  2. Trip_ID
  3. 100001
  4. 100002
  5. 100003
  6. ....
  7.  
  8. Actions
  9. Trip_ID Action MatNr RoOr RoVlg OrderID
  10. 100001 1 10 10 1 394798
  11. 100001 1 10 20 1 657748
  12. 100001 1 10 30 1 657748
  13. 100001 1 10 40 1 394798
  14. 100001 1 10 50 1 10142
  15. 100001 1 10 60 1 6577
  16. 100001 1 10 70 1 6577
  17. 100001 1 10 80 1 10412
  18. 100001 1 10 90 1 975147
  19. 100001 1 10 100 1 975147

(动作:1 =加载,4 =卸载)
MatNr,RoOr和RoVlg的组合是Trip的顺序.

  1. Orders
  2. OrderID LoadingPlace UnloadingPlace
  3. 6577 Thessaloniki Athens
  4. 10142 Thessaloniki Athens
  5. 394798 Paris Thessaloniki
  6. 657748 Milan Athens
  7. 975147 Thessaloniki Paris

解决方法

试试这个.没有变数,没什么特别的花哨:
  1. select a1.action,a1.place
  2. from trip_a a1
  3. left join trip_a a2
  4. on a2.trip_order =
  5. (select min(trip_order)
  6. from trip_a a3
  7. where trip_order > a1.trip_order)
  8. where a1.action != a2.action or a1.place != a2.place or a2.place is null

在这里演示:http://sqlfiddle.com/#!9/4b6dc/13

希望它适用于你正在使用的任何sql,它应该,只要支持查询.

Tt只是找到下一个最高的trip_id,并加入它,或者如果没有更高的trip_order则加入null.然后,它仅选择地点,操作或两者不同的行,或者如果连接表中没有位置(a2.place为null).

标准完全改变后编辑

如果要获得完全从基表构建的相同结果,可以执行以下操作:

  1. select
  2. case when a.action = 1 then 'load' when a.action = 0 then 'unload' end as action,case when a.action = 1 then o.loadingplace when a.action = 0 then o.unloadingplace end as place
  3. from trips t
  4. inner join actions a
  5. on t.trip_id = a.trip_id
  6. inner join orders o
  7. on a.orderid = o.orderid
  8. left join actions a2
  9. on a2.roor =
  10. (select min(roor)
  11. from actions a3
  12. where a3.roor > a.roor)
  13. left join orders o2
  14. on a2.orderid = o2.orderid
  15. where a.action != a2.action
  16. or a2.action is null
  17. or
  18. case when a.action = 1 then o.loadingplace != o2.loadingplace
  19. when a.action = 0 then o.unloadingplace != o2.unloadingplace
  20. end
  21. order by a.roor asc

这是一个更新的小提琴:http://sqlfiddle.com/#!9/fdf9c/14

猜你在找的MsSQL相关文章