2011-09-20 123 views
3

數我所說的表日曆和數據的模樣:計算周

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 

我要計算在MONTH_YEAR週數:

我寫了類似的查詢:

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 

這是給我我想要什麼,但有沒有更好的方法呢?

回答

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 
+0

您可以通過32秒打我,哎呀! :) –

+0

@JNK不,這是不是我想要的例如在上面的數據otput應該返回我3自Month_year 01/1997有三個星期了。 – Peter

+2

@彼得 - 它是什麼回報呢? – JNK

1

我,這是你所需要的:

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

nope這不是我想要的例如在上面的數據otput應該返回我3自Month_year 01/1997有三個星期。 – Peter

+1

@Peter你試過運行過嗎?我確實返回3於01/1997! –

+1

+1 - 絕對基於我們給出的樣本數據工作 – JNK