开发者

Calculate Number of weeks

I Have a table called Calendar and the data looks Like开发者_开发技巧:

Date                         Week_Num       Month_Year
1996-01-27 00:00:00.000      1021            01/1997
1996-01-28 00:00:00.000      1021            01/1997
1996-01-29 00:00:00.000      1021            01/1997
1996-02-03 00:00:00.000      1022            01/1997
1996-02-04 00:00:00.000      1022            01/1997
1996-02-10 00:00:00.000      1023            01/1997
1996-02-11 00:00:00.000      1023            01/1997

I want to calculate the Number of weeks in a month_year:

I wrote a query like:

Select Month_year,Count(*)
From (Select Week_Num,Month_year
      From Calendar
      Group By Week_Num,Month_year
      )a
Group By Month_year
order by Month_year

This is giving me what I want but is there a better way of doing it?


SELECT Month_Year, COUNT(DISTINCT Week_Num)
FROM Calendar
GROUP BY Month_Year

This removes one level of aggregation and is much more readable. I'm not sure if it would perform any better, though.

SAMPLE FOR PROOF OF CONCEPT:

DECLARE @t table (DT smalldatetime, week_num int, month_year varchar(100))

INSERT INTO @t
VALUES
('1996-01-27 00:00:00.000', 1021,'01/1997'),
('1996-01-28 00:00:00.000', 1021,'01/1997'),
('1996-01-29 00:00:00.000', 1021,'01/1997'),
('1996-02-03 00:00:00.000', 1022,'01/1997'),
('1996-02-04 00:00:00.000', 1022,'01/1997'),
('1996-02-10 00:00:00.000', 1023,'01/1997'),
('1996-02-11 00:00:00.000', 1023,'01/1997')

SELECT Month_Year, COUNT(DISTINCT Week_Num)
FROM @t
GROUP BY Month_Year

Returns:

Month_Year  (No column name)
01/1997         3


I this is what you need:

Select Month_year,Count(distinct Week_Num)
From Calendar
Group By Month_year
order by Month_year
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜