【问题标题】:SQL select query comparing multiple rows against 2 columnsSQL选择查询比较多行与2列
【发布时间】:2015-08-07 04:39:16
【问题描述】:

我正在尝试编写一个 SQL 选择查询来解决以下问题。我有一个客户列表,其中包含显示帐户开立日期和帐户关闭日期的帐户。我需要根据客户是否在 2014 年 9 月 30 日之前拥有连续会员资格(即开户)来确定他们是否有资格投票。如果他们在开设新帐户的同一天关闭帐户,则连续会员资格将被计算在内。我的初始表如下:

CUS_ID | ACC_ID | OPEN_DT | CLOSE_DT
1 | 1001 | 01/01/2010 | 01/12/2013
1 | 1002 | 10/03/2014 | 01/11/2014
1 | 1003 | 01/11/2014 | 01/01/2015
1 | 1004 | 01/01/2015 | NULL
2 | 1005 | 01/01/2014 | 10/08/2014
2 | 1006 | 10/08/2014 | 01/02/2015
2 | 1007 | 05/02/2015 | NULL
3 | 1008 | 01/10/2014 | NULL
4 | 1009 | 01/09/2014 | 31/03/2015

您可以看到,客户 1 自 2014 年 10 月 3 日以来一直拥有会员资格,因此符合条件。 客户 2 不符合资格,因为会员资格中断并且他的最新账户是在 2014 年 9 月 30 日之后开设的。 客户 3 没有资格,因为他的帐户是在 2014 年 9 月 30 日之后开设的。客户 4 没有资格,因为帐户已关闭。

我的结果应该是这样的:

CUS_ID | ELIGIBLE
1 | Y
2 | N
3 | N
4 | N

我已尝试将表格连接到自身并将开放日期与关闭日期进行比较,但在某些情况下,每位客户需要检查超过 2 条记录。任何帮助将不胜感激。

【问题讨论】:

  • 对于客户 1 也有中断

标签: sql sql-server select


【解决方案1】:

递归 CTE 是一个不错的选择。

这是我的查询,但我没有进行任何测试,可能需要进行一些调试。

    with a as
(
select CUS_ID , OPEN_DT  
from tab as t1 
where CLOSE_DT is null

UNION ALL

select cus_id, open_dt 
    from table1 as t2
        inner join A as A1
            on A1.CUS_ID = T2.Cust_ID AND A1.Open_dt = t2.close_dt
)

Select Cust_id, Eligible case when MIN(open_dt) < '2014-09-30' then 'Y' else 'N' from a group by Cust_id            

【讨论】:

    【解决方案2】:

    如果记录不重叠(就像您的示例数据一样),您可以使用一个小技巧。计算自您感兴趣的日期以来的天数。然后将每个客户记录的记录中的天数相加。如果这些相等,则涵盖所有日期。

    实现这一点需要一些逻辑,但想法如下:

    select cus_id,
           (case when sum(datediff(day,
                                   (case when open_dt < thedate then thedate else open_dt end),
                                   (case when close_dt > today or close_dt is null then today else close_dt end)
                                  )) =
                      sum(datediff(day, thedate, today))
                 then 'y' else 'n'
            end) as eligible
    from table t cross join
         (select cast('2014-09-30' as date) as thedate,
                 cast(getdate() as date) as today) as params
    where close_dt is null or close_dt >= thedate
    group by cus_id;
    

    【讨论】:

      猜你喜欢
      • 2021-07-14
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-12
      • 2011-06-28
      • 1970-01-01
      相关资源
      最近更新 更多