SQL - 按年,月,日分组的日期

时间:2016-10-05 11:00:57

标签: sql sql-server tsql date

执行查询时

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

我得到了这张桌子:

('A1','2014-03-05','2014-07-21'),
('A1','2014-07-25','2015-03-15'),
('A1','2015-03-17','2016-03-17'),
('B1','2015-04-18','2016-06-16'),
('C1','2015-04-21','2016-02-12'),
('C1','2016-02-14','2016-08-29')

enter image description here

我想计算日期[From date][To date]之间的差异并获取下一张表格:

Item   Year    NoOfMonth  NoOfDays
A1    2014       9          ...
A1    2015       ...        ...
........

Group by Year and item
  • NoOfMonts是按年份和项目的数量
  • NoOfDays是按年份和项目的天数。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您可以使用日历表和一些日期函数:

;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)

输出:

Item    Year    NoOfMonth   NoOfDays
A1      2014    9           22
A1      2015    11          28
A1      2016    2           16
B1      2015    8           13
B1      2016    5           15
C1      2015    8           10
C1      2016    7           26

修改

受此question的启发。

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添加到月份