0
votes

Comment obtenir le nombre de jours restants dans le mois à partir d'une date donnée

Je veux le nombre de jours à partir du 25/02/2019 du mois de février et le résultat attendu est 4

J'ai essayé d'utiliser master ..spt_values ​​ dans le serveur sql mais n'a pas obtenu le résultat attendu

declare @fdays int ,@d date=cast('20190201' as date),@JoinDate date=cast('20190225' as date)
select count(dateadd(dd,number,@d)) from master..spt_values
where type = 'p'
and month(dateadd(dd,number,@d))=month(@d)
and year(dateadd(dd,number,@d))=year(@d)    
and cast(GETDate() as date)>= Cast(dateadd(dd,number,@JoinDate) as date )

Le résultat du code ci-dessus est 28 mais je veux 4

S'il vous plaît aidez-moi à trouver le résultat attendu


1 commentaires

3 Réponses :


3
votes

Il s'agit d'une simple arithmétique de date, vous n'avez pas besoin d'utiliser spt_values:

+------------+-------------------------+----------------------+
| MonthsDiff |  StartOfFollowingMonth  | DaysBetweenGivenDate |
+------------+-------------------------+----------------------+
|       1429 | 2019-03-01 00:00:00.000 |                    4 |
+------------+-------------------------+----------------------+

Output:

declare @d date = '20190225';

select datediff(month,0,@d) as MonthsDiff   -- Months since an arbitrary date
      ,dateadd(month,datediff(month,0,@d)+1,0) as StartOfFollowingMonth -- Add months above +1 to same arbitrary date
      ,datediff(day,@d,dateadd(month,datediff(month,0,@d)+1,0)) as DaysBetweenGivenDate -- DATEDIFF between given date and start of month from above;


0 commentaires

0
votes

Essayez ceci:

 declare @date date='20140603'
    select datediff(day, @date, dateadd(month, 1, @date))-day(@date)


0 commentaires

0
votes

À partir de SQL Server 2012, vous pouvez simplement utiliser la fonction EOMONTH:

SELECT DATEDIFF(DAY, '20190225', EOMONTH ('20190225')) + 1 [thedays]

= 4.


0 commentaires