How to use DATEDIFF? How many days are inside of two dates

懵懂的女人 提交于 2020-02-05 05:14:28

问题


How to use DATEDIFF? How can I make this to work? or should I use DATEDIFF completly differently?

SELECT DATEDIFF('Started ','will_end') AS 'Duration' FROM my_table WHERE id = '110';

I try to get answer, how many days are inside of two dates.

I would like to get an aswer like:
Duration = 7 days;

I have this kind of database:

Started | will_end
2009-12-17 | 2009-12-24
2009-12-12 | 2009-12-26


回答1:


Put will_end first, started second:

SELECT  DATEDIFF('2009-12-24', '2009-12-17') 

---
  7

Also, remove the single quotes from your field names:

SELECT  DATEDIFF(will_end, started) AS Duration
FROM    my_table
WHERE   id = 110

, or replace them with the backticks:

SELECT  DATEDIFF(`will_end`, `started`) AS `Duration`
FROM    `my_table`
WHERE   `id` = 110



回答2:


Are you getting a NULL result? You have the column names in single quotes in your query, which means you are passing the strings 'Started ' and 'will_end' to DATEDIFF rather than the column values. Try removing the single quotes, and you will start to see some results:

SELECT DATEDIFF(Started, will_end) AS Duration FROM my_table WHERE id = '110';

Note that this will give you a negative result. To get a positive result, reverse the order of the columns:

SELECT DATEDIFF(will_end, Started) AS Duration FROM my_table WHERE id = '110';



回答3:


replace the order

DATEDIFF('will_end','Started')




回答4:


I think there are 3 parameter to be passed in DATEDIFF ( datepart , startdate , enddate )

so your code would be DATEDIFF ( dd , 'Started ','will_end' )

http://msdn.microsoft.com/en-us/library/ms189794.aspx



来源:https://stackoverflow.com/questions/1946490/how-to-use-datediff-how-many-days-are-inside-of-two-dates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!