all groups > sql server new users > april 2007 >
You're in the

sql server new users

group:

Sales within the first year


Sales within the first year Vayse
4/17/2007 12:00:00 AM
sql server new users:
I have a Client table, with a field StartDate
I also have a Sales table. There is a field called SaleDate.
I'd like to run a query, and flag any Sales within one year of the Clients
start date as New Business.
I thought I'd just this would be easy - use DateDiff, but I was wrong!

For example:
Client Start Date = 12/04/06 - 12th April 2006

Sale Date = 04/04/06
DATEDIFF(m, dbo.Clients.Client_StartDate, dbo.Sales.SaleDate) = 12
Sale Date = 13/04/06
DATEDIFF(m, dbo.Clients.Client_StartDate, dbo.Sales.SaleDate) = 12

So I get 12 months in both cases. As it states in the T-SQL help:
DateDiff - Returns the number of date and time boundaries crossed between
two specified dates.

So what should I use instead of DateDiff?

Thanks
Vayse

Re: Sales within the first year TheSQLGuru
4/17/2007 10:23:29 AM
How about DAYs for the datediff? If <365, you have a new client.

--
TheSQLGuru
President
Indicium Resources, Inc.

[quoted text, click to view]

Re: Sales within the first year Vayse
4/17/2007 4:38:47 PM
That did occur to me, but I couldn't figure out how to deal with leap years.
Still can't!

[quoted text, click to view]

Re: Sales within the first year Hugo Kornelis
4/17/2007 11:13:59 PM
[quoted text, click to view]

Hi Vayse,

You can use the formula below to calculate the difference in "real"
years (found on
http://classicasp.aspfaq.com/date-time-routines-manipulation/given-two-dates-how-do-i-determine-an-age.html)

DECLARE @birthdate SMALLDATETIME, @endDate SMALLDATETIME
SET @birthdate = '19740224'
SET @endDate = GETDATE()

SELECT DATEDIFF
(
YEAR,
@birthdate,
@endDate
) - CASE
WHEN 100 * MONTH(@endDate) + DAY(@endDate)
< 100 * MONTH(@birthdate) + DAY(@birthdate)
THEN 1 ELSE 0 END


--
Hugo Kornelis, SQL Server MVP
Re: Sales within the first year Vayse
4/20/2007 12:00:00 AM
That should do it, thanks.

[quoted text, click to view]

Re: Sales within the first year TheSQLGuru
4/27/2007 11:38:23 PM
Isn't there a simple formula for calculating if any given year is a leap
year? Something like divisible by 4 but not 100 or some such. Anyway, no
matter what it is (and I KNOW it exists and is simple), just use a CASE
statement to test the year of concern and factor it into the overall
datediff math.

--
TheSQLGuru
President
Indicium Resources, Inc.

[quoted text, click to view]

Re: Sales within the first year Hugo Kornelis
4/28/2007 12:00:00 AM
[quoted text, click to view]

Hi SQLGuru,

Rule:
If divisible by 4 --> leapyear

Exception to rule:
If divisible by 100 --> not a leapyear

Exception to exception:
If divisible by 400 --> not a leapyear

Or in T-SQL:
IF @Year % 400 = 0
OR (@Year % 4 = 0 AND @Year % 100 <> 0)
SET @Leap = 'Yes';
ELSE
SET @Leap = 'No';

--
Hugo Kornelis, SQL Server MVP
AddThis Social Bookmark Button