我有一个名为Calendar的表,数据看起来像:
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
我想计算一个月内的周数:
我写了一个像:
这样的查询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
这给了我想要的东西但是有更好的方法吗?
答案 0 :(得分:4)
SELECT Month_Year, COUNT(DISTINCT Week_Num)
FROM Calendar
GROUP BY Month_Year
这将删除一个级别的聚合,并且更具可读性。不过,我不确定它是否会有更好的表现。
证明概念的样本:
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
<强>返回:强>
Month_Year (No column name)
01/1997 3
答案 1 :(得分:1)
我这就是你所需要的:
Select Month_year,Count(distinct Week_Num)
From Calendar
Group By Month_year
order by Month_year