sql - 在 SQL 中选择当前列值与先前值不匹配的行

标签 sql sql-server sql-server-2012

我有一张订单表。在此表中,除其他行外,我有一个 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/

相关文章:

C# ADO.net 查询运行缓慢

visual-studio-2010 - 发布 SQL Data Tools 2012 项目 : Forces into Single User Mode

sql - 转置数据以创建表

java - 使用 Select Case 进行 JPA 条件查询

MySQL INSERT ... SET ... ON DUPLICATE KEY 失败...困惑

SQL JOIN : is there a difference between USING, ON 或 WHERE?

sql-server - 如何为 SQL Server 中的连接设置排序规则?

sql - 使用 with 语句创建 View

.net - Python vs C#/.NET——使用 Python 开发大型 Web 应用程序需要考虑的主要区别是什么?

c# - 将 DateTime 插入 sql server 2008 时出现奇怪的错误