按每月最新日期分组数据

时间:2016-11-02 10:54:19

标签: sql sql-server

我每天都会在下表中存储数据

CREATE TABLE dbo.DemoTable
(
    ReportDate                  DATE                NOT NULL,
    IdOne                       INT                 NOT NULL,
    IdTwo                       INT                 NOT NULL,
    NumberOfThings              INT                 NOT NULL DEFAULT 0

    CONSTRAINT PK_DemoTable PRIMARY KEY NONCLUSTERED (ReportDate, IdOne, IdTwo)
)

我想报告此事,但只提取每月最新日期的数据(NumberOfThings的总和)。

示例数据

INSERT INTO DemoTable
(ReportDate, IdOne, IdTwo, NumberOfThings)
VALUES
('2016-11-02',1,2,2),   ('2016-11-02',1,3,2),   ('2016-11-01',1,2,20),  ('2016-11-01',1,3,20),
('2016-10-31',1,2,2),   ('2016-10-31',1,3,2),   ('2016-10-30',1,2,20),  ('2016-10-30',1,3,20),  ('2016-10-29',1,2,200), ('2016-10-29',1,3,200),
('2016-09-30',1,2,5),   ('2016-09-30',1,3,5),   ('2016-09-29',1,2,55),  ('2016-09-29',1,3,55)

所以对于这个数据,我想看看:

 2016-11-02 | 4 
 2016-10-31 | 4
 2016-09-30 | 10

由于

4 个答案:

答案 0 :(得分:4)

您可以使用RANK()查看每个月的最新日期行,并将它们相加。

SELECT s.ReportDate,SUM(s.NumberOfThings)
FROM (
    SELECT t.*,
           RANK() OVER(PARTITION BY YEAR(t.ReportDate), MONTH(t.ReportDate) ORDER BY t.ReportDate DESC) as rnk
    FROM DemoTable t) s
WHERE s.rnk = 1
GROUP BY s.ReportDate

答案 1 :(得分:1)

您可以使用此类查询

select ReportDate, sum(NumberofThings) as SumNumberofThings from DemoTable where ReportDate in
(
select   max(ReportDate) MaxReportDate from DemoTable
group by datepart(yy,reportdate), datepart(m,reportdate)
)
group by ReportDate

答案 2 :(得分:0)

一种典型的方法涉及row_number()。唯一的技巧是使用日期函数来获取年份和月份:

select dt.*
from (select dt.*,
             row_number() over (partition by year(ReportDate), month(ReportDate)
                                order by ReportDate desc
                               ) as seqnum
      from DemoTable dt
     ) dt
where seqnum = 1;

如果每个日期有重复项,您只需对聚合执行相同的操作:

select dt.ReportDate, dt.NumberOfThings
from (select dt.ReportDate, sum(NumberOfThings) as NumberOfThings,
             row_number() over (partition by year(ReportDate), month(ReportDate)
                                order by ReportDate desc
                               ) as seqnum
      from DemoTable dt
      group by NumberOfThings
     ) dt
where seqnum = 1;

答案 3 :(得分:0)

汇总您的数据,以获得每个日期的总和。然后在月内按日期对记录进行排名。然后选择排名最高的记录。

SELECT
  ReportDate, 
  SumNumberOfThings
FROM
(
  SELECT 
    ReportDate, 
    ROW_NUMBER() OVER (PARTITION BY YEAR(ReportDate), MONTH(ReportDate)
                       ORDER BY ReportDate DESC) AS rn
    SUM(NumberOfThings) AS SumNumberOfThings
  FROM DemoTable
  GROUP BY ReportDate
) ranked
WHERE rn = 1
ORDER BY ReportDate;