摆脱查询中的“半重复”

时间:2013-05-20 20:46:00

标签: sql sql-server-2008 duplicates

我目前有一个返回的查询,例如,以下内容:(您可以假设这是表结构的样子)

customer_id | start_date | end_date
1           | 20120101   | 20120401
2           | 20120402   | 20121231
1           | 20130101   | 20130401
1           | 20130101   | 20130330
2           | 20130331   | 99991231
2           | 20130402   | 99991231

有两点需要考虑:

  1. 客户可以回来,因此对此采取正常的最大/最小方法是行不通的。
  2. 这实际上是多个服务的概述,有时其中一个服务在不同的日期开始或结束。 (非常罕见,但我需要处理这种情况。)
  3. 因此,考虑到上述情况,我想要一个将返回第1行,第2行,第3行和第5行的查询。

    我的想法&对此的处理方法是:

    • 如果start_dates相等,则显示最大结束日期。 (group by customer_id& start_date,max(end_date))
    • 如果end_dates相等,则显示最小开始日期。 (group by customer_id& end_date,min(start_date))

    我可以编写一个可以执行上述操作之一的查询,但我不确定如何能够同时执行这两个操作。或者如果完全不同的方法会更好。

    SQL Server 2008

    谢谢!

1 个答案:

答案 0 :(得分:0)

我认为您可以使用not exists条件 -

执行此操作

您可以使用以下查询进行此输出 -

select customer_id , start_date , end_date
from table_name t_1 
where not exists(
  select 1 from table_name t_2 
  where t_2.customer_id = t_1.customer_id
  and t_2.start_date = t_1.start_date
  and t_2.end_date > t_1.end_date) 
and not exists (
  select 1 from table_name t_3 
  where t_3.customer_id = t_1.customer_id
  and t_3.end_date = t_1.end_date
  and t_3.start_date<t_1.start_date)
相关问题