如果我有开始日期和已经过去的天数,那么用于计算每年的天数的SQL将是什么?
例如,日期(ymd)2013-01-01和经过的天数为1000。
我希望结果看起来像这样
2013 = 365
2014 = 365
2015 = 270
这可以写成datediff
之类的函数吗?
我尝试过使用日历表,但是当然,链接到该表只会给我2013 = 1000
我的日历表如下所示。
DATE_ID | DATE | CALENDAR_YEAR | FINANCIAL_YEAR
-----------------------------------------------
20130101 | 2013-01-01 | 2013 | 2013/14
这是我尝试过的。
选择
D.FISCAL_YEAR,SUM([DAYS])为NUMBER_OF_DAYS
FROM [dbo]。[FACT] F
左联接[dbo]。[DIM_DATE] D ON D.DATE_ID = F.DATE_ID
组别
D.FISCAL_YEAR
结果是
FISCAL_YEAR | NUMBER_OF_DAYS
----------------------------
2013/14 |2820
2014/15 |6635
2015/16 |2409
答案 0 :(得分:0)
我会亲自建立一个理货表格来完成此任务。建立好后,您可以轻松获得每个日期并计算每年的天数:
$sql= "INSERT INTO ponto (hora_entrada,saida_almoco,entrada_tarde,hora_saida,cod_colab) VALUES (". (null === $horaEntrada ? "NULL" : "'$horaEntrada'") . ", '".$saidaAlmoco."', '".$entradaTarde."', '".$horaSaida."', '".$cod_colab."')";
功能:
DECLARE @YMD date = '20130101',
@Lapsed int = 1000;
--Build a Tally table
WITH N AS(
SELECT N
FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL)) N(N)),
Tally AS(
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1 AS I
FROM N N1, N N2, N N3, N N4), --10,000 should be enough
--Build the dates table
Dates AS(
SELECT DATEADD(DAY, T.I, @YMD) AS CalendarDate
FROM Tally T
WHERE T.I <= @Lapsed - 1)
--And count the days
SELECT DATEPART(YEAR, CalendarDate) AS Year,
COUNT(CalendarDate) AS Days
FROM Dates D
GROUP BY DATEPART(YEAR, CalendarDate);
答案 1 :(得分:0)
一种方法是递归CTE:
with dates as (
select v.d, 1000 - datediff(day, v.d, dateadd(year, 1, v.d)) as days
from (values (datefromparts(2013, 1, 1))) v(d)
union all
select dateadd(year, 1, d), days - datediff(day, d, dateadd(year, 1, d))
from dates
where days > 0
)
select d,
(case when days > 0 then datediff(day, d, dateadd(year, 1, d))
else datediff(day, d, dateadd(year, 1, d)) + days
end)
from dates;
Here是db <>小提琴。