我有一张订单表。在此表中,除其他行外,我有一个 ID (PK)、客户 ID、发货国家和订单日期
ID | CustomerId | ShippingCountry | OrderDate
1 | 111111 | DE | 2016-08-13
2 | 222222 | GB | 2016-08-17
3 | 111111 | ES | 2016-09-05
4 | 333333 | ES | 2016-10-25
5 | 444444 | US | 2016-10-26
6 | 555555 | FR | 2016-10-29
7 | 666666 | DE | 2016-11-04
8 | 111111 | DE | 2016-11-12
9 | 222222 | US | 2016-12-01
10 | 444444 | GB | 2016-12-01
11 | 555555 | FR | 2016-12-05
12 | 333333 | ES | 2016-12-15
我需要选择客户之前的订单与其最新订单的发货国家/地区不匹配的行。我还想在结果中看到 2 个不同的运输代码。
使用上面的例子,我想看到:
CustomerId | ShippingCountryLatest | ShippingCountryPrevious
111111 | DE | ES
222222 | US | GB
444444 | GB | US
ID 和 OrderDate 可用于确定事物的顺序。 ID是一个递增的数字,订单日期就是它所说的。
我需要运行它的表有大约 50 万行。
有什么建议吗?
这是一个帮助您入门的 SQLFiddle:http://sqlfiddle.com/#!6/5d046/1/0
最佳答案
使用 ROW_NUMBER
为每个客户提供最新记录 #1 和之前的 #2。然后汇总每个客户并比较两个值。
select
CustomerId,
max(case when rn = 1 then ShippingCountry end) as ShippingCountryLatest,
max(case when rn = 2 then ShippingCountry end) as ShippingCountryPrevious
from
(
select
CustomerId,
ShippingCountry,
row_number() over (partition by CustomerId order by ID desc) as rn
from orders
) numbered
group by customerid
having
max(case when rn = 1 then ShippingCountry end) <>
max(case when rn = 2 then ShippingCountry end);
你的 fiddle 回来了:http://sqlfiddle.com/#!6/5d046/13 :-)
关于sql - 在 SQL 中选择当前列值与先前值不匹配的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43374888/