Friday, March 23, 2012

Minimum/Maximum of two values

Hallo Cracks,

what I try is a little bit heavy, maybe, but I only miss the minimum/maximum fuction - or I didn´t found it; not here in the Forum and also not in the onlinehelp of the SQL Server.

What I try to do:

I have 2 columns in my table; a start- and an end-date. For this period of time between end and start i have to calculate the days for the years. Here my thoughts (for the current year):

Is the startdate <= 31.12.2004 and the enddate >= 1.1.2004 i have to calculate die datediff between max(1.1.2004/startdate) and min(31.12.2004/enddate)

like this sqlstatement:

SELECT CASE WHEN dbo.Phases.phasenstart <= CAST(CAST(YEAR(GETDATE()) AS
varchar) + '-31-12' AS smalldatetime) AND dbo.Phases.phasenabschlussist >=
CAST(CAST(YEAR(GETDATE()) AS varchar) + '-01-01' AS smalldatetime)
THEN 365 ELSE 0 END AS Expr2,
FROM dbo.Phases
WHERE (phasenstart IS NOT NULL) AND (phasenabschlussist IS NOT NULL)

instead of 365 there must be the above calculation. Is start=3.1.2003 and end=30.1.2004 I expect as result only the 30 days in 2004.

thanks in advance and kind regards :-)
Cappuhave a look at MAX, MIN, and DATEDIFF functions in SQL Server Books Online|||thanks, but Max and Min exists only as aggregate functions.

I have a solution now with CASE, it works but it looks terrible ;-)

here is it:

SELECT CASE WHEN dbo.Phases.phasenstart <= CAST(CAST(YEAR(GETDATE()) AS varchar) + '-31-12' AS smalldatetime) AND
dbo.Phases.phasenabschlussist >= CAST(CAST(YEAR(GETDATE()) AS varchar) + '-01-01' AS smalldatetime) THEN DATEDIFF(day,
CASE WHEN dbo.Phases.phasenstart >= CAST(CAST(YEAR(GETDATE()) AS varchar) + '-01-01' AS smalldatetime)
THEN dbo.Phases.phasenstart ELSE CAST(CAST(YEAR(GETDATE()) AS varchar) + '-01-01' AS smalldatetime) END,
CASE WHEN dbo.Phases.phasenabschlussist <= CAST(CAST(YEAR(GETDATE()) AS varchar) + '-31-12' AS smalldatetime)
THEN dbo.Phases.phasenabschlussist ELSE CAST(CAST(YEAR(GETDATE()) AS varchar) + '-31-12' AS smalldatetime) END)
+ 1 ELSE 0 END AS TageISTJahr0
FROM dbo.Phases´

it works, but do i understand in two years what i did there? ;-)

No comments:

Post a Comment