在MSSQL中比较SQL Rows?

时间:2014-04-06 11:02:26

标签: sql sql-server database union jointable

我刚刚启动SQL并且在解决以下SQL方面遇到问题 - > 我们有一个3列的客户表,需要在日期列的基础上进行比较。

  • 每位客户都有申请日期,我们需要在接下来的7天内再次收到申请的客户。
  • 创建一个新列,其中set flag为1,其中应用程序在过去7天内收到。

数据:

Customer_ID  | App_ID (PK)| App_Date
200               13    12/28/2013
200               23    12/26/2013
300               11    12/15/2013
200               54    12/15/2013
300               32    12/15/2013
200                9    12/2/2013
100                6    12/22/2013

答案:

Customer_ID  | App_ID (PK)| App_Date   | Flag
200               13    12/28/2013 
200               23    12/26/2013    1
300               11    12/15/2013
200               54    12/15/2013    1
300               32    12/15/2013    1
200                9    12/2/2013
100                6    12/22/2013

感谢。

2 个答案:

答案 0 :(得分:0)

您可以使用first_value分析功能查找每位客户的最早日期。从那以后,这只是减去日期的问题:

SELECT customer_id, app_id, app_date,
       CASE WHEN DATEDIFF (day, first_date, app_date) > 7 THEN 1 
            ELSE null END 
       AS flag
FROM   (SELECT customer_id, app_id, app_date, 
               FIRST_VALUE (app_date) OVER 
                  (PARTITION BY customer_id ORDER BY app_date ASC) AS first_date
        FROM   my_table) t

答案 1 :(得分:0)

测试数据

DECLARE @TABLE TABLE(Customer_ID INT,App_ID INT,App_Date DATE)
INSERT INTO @TABLE VALUES
(200,13,'12/28/2013'),(200,23,'12/26/2013'),(300,11,'12/15/2013')
,(200,54,'12/15/2013'),(300,32,'12/15/2013'),(200, 9,'12/2/2013')
,(100, 6,    '12/22/2013')

<强>查询

; WITH CTE
AS (
     SELECT * 
       ,ROW_NUMBER() OVER (PARTITION BY Customer_ID ORDER BY App_Date) rn
     FROM @table
    )
SELECT C1.Customer_ID
      ,C1.App_ID
      ,C1.App_Date
      ,CASE WHEN DATEDIFF(DAY, C1.App_Date, C2.App_Date) <= 7 
            THEN 1 ELSE NULL END AS Flag
FROM CTE C1 LEFT JOIN CTE C2
ON C1.rn = C2.rn + 1
AND C1.Customer_ID = C2.Customer_ID

结果集

╔═════════════╦════════╦════════════╦══════╗
║ Customer_ID ║ App_ID ║  App_Date  ║ Flag ║
╠═════════════╬════════╬════════════╬══════╣
║         100 ║      6 ║ 2013-12-22 ║ NULL ║
║         200 ║      9 ║ 2013-12-02 ║ NULL ║
║         200 ║     54 ║ 2013-12-15 ║ 1    ║
║         200 ║     23 ║ 2013-12-26 ║ 1    ║
║         200 ║     13 ║ 2013-12-28 ║ 1    ║
║         300 ║     11 ║ 2013-12-15 ║ NULL ║
║         300 ║     32 ║ 2013-12-15 ║ 1    ║
╚═════════════╩════════╩════════════╩══════╝