tsql proc逻辑帮助

时间:2010-04-19 14:35:32

标签: sql sql-server-2005 tsql

我在SQL方面很弱,需要一些帮助来处理我的proc。

三件:存储过程,table1,table2

表1列出了特定ID的最新数据

Customer_id status_dte  status_cde    app_dte
001         2010-04-19  Y             2010-04-19

表2列出了特定客户ID的数据历史记录: 例如:

Log_id  customer_Id status_dte  status_cde
01     001         2010-04-20   N
02      001         2010-04-19   Y      
03      001         2010-04-19   N
04      001         2010-04-19   Y

如果状态为日期,则存储的proecure当前会抛出错误 table1是<比表1中的app_date。

If @status_dte < app_date
    Error

注意:@status_dte是一个存储为table1

的status_dte的变量

但是,我希望它在EARLIEST status_dte来自时抛出错误 status_cde为'Y'的表2小于app_dte列 表1。

请记住,这个最早的日期并不存储在历史的任何地方 每个客户的数据变化。另一位客户可能会有以下情况 历史。

Log_id  customer_Id status_dte  status_cde
01     002         2010-04-20  N
02      002         2010-04-18  N       
03      002         2010-04-19  Y
04      002         2010-04-19  Y

关于如何处理这个问题的任何想法?

2 个答案:

答案 0 :(得分:0)

您可以按照每个客户一次性测试,找到最早的日期小于使用此构造的appdate的位置

IF EXISTS (SELECT *
    FROM
      mytable M
      JOIN
      HistoryTable H ON M.customer_Id = H.customer_Id
    WHERE
      H.status_cde = 'Y'
    GROUP BY
      H.customer_Id, M.app_dte
    HAVING
     MIN(H.status_dte) < M.app_dte)
  ...error...

答案 1 :(得分:0)

如果您想要一个客户列表,而不是单个客户,而是在app_date之前的最早状态日期,那么您可以执行以下操作:

;With 
    CustomerStatusDates As
    (
        Select T2.customer_id, Min(T2.status_dte) As MinDate
        From Table2 As T2
        Where status_cte = 'Y'
        Group By T2.customer_id
    )
Select ....
From Table1 As T1
    Join CustomerStatusDates As T2
        On T2.Customer_Id = T1.Customer_Id
Where T2.MinDate < T1.app_dte
相关问题