Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 780
Peter Avatar asked Dec 09 '25 14:12

Peter


1 Answers

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
like image 179
JNK Avatar answered Dec 12 '25 06:12

JNK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!