Question

I have just started SQL and have problem in solving following SQL --> We have a customer table with 3 column and which needed to compared on the basis of date column.

  • Each customer has an application date and we need to get the customers whose application is received again with next 7 days.
  • Create a new column with set flag to 1, where application are received with last 7 days.

Data:

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

Answer:

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

Thanks.

Was it helpful?

Solution

You can use the first_value analytic function to find the earliest date per customer. From there on, it's just a matter of subtracting dates:

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

OTHER TIPS

Test Data

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')

Query

; 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

Result Set

╔═════════════╦════════╦════════════╦══════╗
║ 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    ║
╚═════════════╩════════╩════════════╩══════╝
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top