SQL - 按年,月,日更新日期组

时间:2016-10-06 11:19:15

标签: sql sql-server tsql date

我使用代码来计算两个日期组之间的差异,按年,月,日:

;WITH calendar AS (
SELECT  CAST(MIN([From date]) as datetime) as d,
    MAX([To date]) as e
FROM ItemTable
UNION ALL
SELECT  DATEADD(day,1,d),
    e
FROM calendar
WHERE d < e
), cte AS(
SELECT  i.Item,
    DATEPART(year,c.d) as [Year],
    DATEDIFF(month,MIN(c.d),MAX(c.d)) as NoOfMonth,
    DATEDIFF(day,DATEADD(month,DATEDIFF(month,MIN(c.d),MAX(c.d)),MIN(c.d)), 
  MAX(c.d)) as NoOfDays
FROM ItemTable i
INNER JOIN calendar c
ON c.d between i.[From date] and i.[To date]
GROUP BY i.Item, DATEPART(year,c.d),[From date],[To date]
)

SELECT  Item,
    [Year],
    SUM(NoOfMonth) as NoOfMonth,
    SUM(NoOfDays) as NoOfDays
FROM cte
GROUP BY Item,[Year]
ORDER BY Item
OPTION (MAXRECURSION 0)

我在SQL - date group by year, month, days

中找到了此代码

但不适合我...

执行查询时

SELECT Item,
[From date],
[To date]
 from ItemDate;

我得到了

('A1','2013-08-27','2013-09-27'),
('A1','2013-09-28','2013-11-28'),
('A1','2013-11-30','2013-12-03'),
('A1','2013-12-31','2014-03-31'),
('A1','2014-04-01','2014-07-01'),
('A1','2014-07-02','2014-10-02'),
('A1','2014-10-03','2014-12-31')

以及从此链接执行代码时SQL - date group by year, month, days

我明白了:

 Item      Year         NoOfMonth     NoOfDays 
  A1        2013           4             -27
  A2        2014           10            58

这不好...... 2013年应该是3个月和4天, 并且对于2014年11个月和28天

如何更新代码以获得所需的结果?

1 个答案:

答案 0 :(得分:0)

将最后一个选择更改为:

SELECT  Item,
        [Year],
        CASE WHEN SUM(NoOfDays) < 0 THEN SUM(NoOfMonth)-1 
            WHEN SUM(NoOfDays) > 30 THEN SUM(NoOfMonth)+1 
            ELSE SUM(NoOfMonth) END as NoOfMonth,
        CASE WHEN SUM(NoOfDays) >= 30 THEN SUM(NoOfDays)-30 
            WHEN SUM(NoOfDays) < 0 THEN SUM(NoOfDays)+30
            ELSE SUM(NoOfDays) END as NoOfDays
FROM cte
GROUP BY Item,[Year]
ORDER BY Item
OPTION (MAXRECURSION 0)

此类报告的主要问题 - 很难定义什么是 1个月,DATEDIFF只需要从2个日期开始,然后相互减去。

我选择30作为月份的天数,现在我将天数值与30进行比较,因此如果天数低于零或低于30,我们可以将+1添加到月份