Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Understanding DATEDIFF()
Message
 
 
À
16/04/2015 16:01:44
Information générale
Forum:
Microsoft SQL Server
Catégorie:
Syntaxe SQL
Versions des environnements
SQL Server:
SQL Server 2012
Application:
Web
Divers
Thread ID:
01618557
Message ID:
01618565
Vues:
39
>If I have this:
>
>
>SELECT SUM(DATEDIFF(d,Holiday.Start,Holiday.End))
>
>
>...I can obtain 365.
>
>Now, if I change the type to s, to obtain this same amount in seconds:
>
>
>SELECT SUM(DATEDIFF(s,Holiday.Start,Holiday.End))
>
>
>...I obtain 23533200.
>
>However, If I do 23533200/84600, I do not obtain 365 days but only 272.38.
>
>What am I missing?

The problem here is indirect casting to float and therefore wrong calculations. Try casting to DECIMAL to obtain correct result, e.g.
;with cteDates as (select dateadd(day, n.number, '20000101') as [startDate],
dateadd(day, n.number, '20000102') as [endDate]
from dbo.numbers N where N.number  between 0 and 364)

select SUM(datediff(day, startDate, endDate)) as [Days Count],
SUM(cast(datediff(second, startDate, endDate)  as decimal(12,2))/86400)  as [Days /Seconds Count],
SUM(datediff(second, startDate, endDate))/86400.00  as [Wrong Days /Seconds Count]
from cteDates 
If it's not broken, fix it until it is.


My Blog
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform