Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Update Column

Author  Topic 

stahorse
Yak Posting Veteran

86 Posts

Posted - 2014-02-11 : 02:53:10
I have two tables;

CUSTOMER (customer_id NUMBER, customer_name VARCHAR2(100), recently_purchased VARCHAR2(1))

and

CUST_PRODUCTS (product_id NUMBER, customer_id NUMBER, date_purchased DATE);

I need to update CUSTOMER, to set recently_purchased = 'Y' if product purchased products are in the last 12 months.

I know that two tables has to be joined and I can use CUST_PRODUCTS where DATEDIFF(month,date_purchased, GETDATE()) <= 12, but I can't get my query right. please help.

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2014-02-11 : 03:00:59
[code]
UPDATE c
SET recently_purchased = 'Y'
FROM Customer c
WHERE EXISTS (SELECT 1
FROM CUST_PRODUCTS
WHERE customer_id = c.customer_id
AND date_purchased >= DATEADD(mm,DATEDIFF(mm,0,GETDATE())-12,0)
)
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

Kristen
Test

22859 Posts

Posted - 2014-02-11 : 03:27:34
quote:
Originally posted by stahorse

where DATEDIFF(month,date_purchased, GETDATE()) <= 12



Visakh's code looks fine. You might(??) need to alias the CUST_PRODUCTS table (I'm not sure without trying it). Code below.

Personally I suggest you stick with "month" as the first parameter of DATEDIFF. The short abbreviations are probably fine for folk that use them everyday - but then along comes someone [less skilled] doing code maintenance and they may not spot that an abbreviation is wrong. Is "mm" Month, Minute, Millisecond, Microsecond ? "mm" is the most obvious of those, the others less so ... so here we always use the full parameter name.

UPDATE c
SET recently_purchased = 'Y'
FROM Customer c
WHERE EXISTS (SELECT 1
FROM CUST_PRODUCTS AS P
WHERE P.customer_id = c.customer_id
AND date_purchased >= DATEADD(month,DATEDIFF(month,0,GETDATE())-12,0)
)
Go to Top of Page
   

- Advertisement -