我有具体的日期范围,比如
From Date To Date
---------------------------
2012-11-10 2012-11-15
2012-11-21 2012-11-22
2012-11-30 2012-12-01我想编写一个SQL查询,它计算两个日期之间的总天数,并计算特定月份的总天数
我想要的输出是,
No of days month
--------------------
9 11
1 12有人能帮我写这个SQL查询吗?
发布于 2012-11-28 16:05:57
理想情况下,您有一个名为“date”的表,其中包含您将使用的所有日期,例如从1950年到2100年。此查询将给出您想要的结果:
select dateadd(m,datediff(m, 0, d.thedate),0) themonth, count(1)
from dates d
join ranges r on d.thedate between r.[from date] and r.[to date]
group by datediff(m, 0, d.thedate)
order by themonth;结果:
| themonth | COLUMN_1 |
-------------------------
| 2012-11-01 | 9 |
| 2012-12-01 | 1 |请注意,此查询不是仅将"11“或" 12”显示为月份,如果范围超过12个月,则不能很好地工作,或者在跨过新的一年时不能帮助排序,而是显示月份的第一天。
如果没有,您可以根据下面的扩展查询动态创建一个dates表:
;with dates(thedate) as (
select dateadd(yy,years.number,0)+days.number
from master..spt_values years
join master..spt_values days
on days.type='p' and days.number < datepart(dy,dateadd(yy,years.number+1,0)-1)
where years.type='p' and years.number between 100 and 150
-- note: 100-150 creates dates in the year range 2000-2050
-- adjust as required
)
select dateadd(m,datediff(m, 0, d.thedate),0) themonth, count(1)
from dates d
join ranges r on d.thedate between r.[from date] and r.[to date]
group by datediff(m, 0, d.thedate)
order by themonth;完整的工作示例在这里:SQL Fiddle
发布于 2012-11-28 15:47:41
尝尝这个
select ((day(date_to)) - (day(date_from))) as no_of_days,month(date_from)as month from tablename 发布于 2012-11-28 15:59:19
请原谅我写的SQL写得不好。
假设月份不同。fromdate和todate之间的值是1。
模式
CREATE TABLE dateData
(fromdate datetime, todate datetime)
;
INSERT INTO dateData
(fromdate, todate)
VALUES
('2012-11-10', '2012-11-15'),
('2012-11-21', '2012-11-22'),
('2012-11-30', '2012-12-01')
;SQL
select mth, sum(days) as daysInMth
from
(
select month(fromdate) as mth,
sum(case
when month(fromdate) = month(todate) then datediff(dd, fromdate, todate)+1
else datediff(dd, fromdate, dateadd(mm, 1, fromdate) - day(fromdate)) + 1 end)
as days
from dateData
group by month(fromdate)
union
select month(todate) as mth,
sum(case when month(todate) <> month(fromdate) then
datediff(dd, fromdate, dateadd(mm, 1, fromdate) - day(fromdate)) + 1
else
case when month(todate) = month(fromdate) then 0 else
datediff(dd, convert(datetime, year(todate) + '-' + month(todate) + '-1'), todate)
end
end) as days
from dateData
group by month(todate)
) aggregated
group by mth在SQLFiddle上查看:http://www.sqlfiddle.com/#!3/9f7da/56
https://stackoverflow.com/questions/13599562
复制相似问题