2015-05-11 79 views
0

我有以下SQL查詢(SQL Server 2008中):如何獲得在SQL查詢一週格式化字符串

SELECT sum(data.freq) as freq,data.week as week FROM (
SELECT 
count(daterequested) as freq, 
datepart(wk,daterequested) as week, 
daterequested 
FROM request ma 
JOIN contracts mc ON (mc.uid= ma.uid) 
JOIN groups og ON og.groupuid = mc.groupuid 
JOIN member m ON (m.memberuid = mc.memberuid) 
WHERE daterequested BETWEEN 
DATEADD(MONTH,-1,GETDATE()) 
AND 
GETDATE() 
AND isdeleted = 0 
GROUP BY datepart(wk,daterequested),daterequested 
--ORDER BY daterequested ASC 
) data 
GROUP BY data.week 

結果是與下列數據的表:

enter image description here

而不是顯示周編號我想顯示格式如下星期:

MM/dd其中MM =月,dd是一週開始的日期。

如果我可以從一週的第一天開始,然後是中間斜線,然後是該周的最後一天,最後是月份,那將會很好:例如:11-17/04(4月11日至17日)等

這裏是最後的表,我想獲得:

enter image description here

任何線索?

+0

要小心,因爲datapart(WK,ADATE)返回年份的周,當你有多個年的數據你的小組由可能不會返回預期的結果。 – Tim3880

回答

0

如果有人需要它只是找到一個解決方案,也許不是最好的,但工程。

SELECT sum(data.freq) as freq, 
data.week as week, CAST(data.weekstart as varchar) + '-' + CAST(data.weekend as varchar) + '/' + CAST(data.monthend as varchar) as formatweek 
FROM (
SELECT 
count(daterequested) as freq, 
datepart(wk,daterequested) as week, 
DATEPART(dd,DATEADD(dd, -(DATEPART(dw, daterequested)-1), daterequested)) weekstart, 
DATEPART(dd,DATEADD(dd, 7-(DATEPART(dw, daterequested)), daterequested)) weekend, 
DATEPART(mm,DATEADD(dd, 7-(DATEPART(dw, daterequested)), daterequested)) monthend, 
daterequested 
FROM requestma 
JOIN contracts mc ON (mc.uid= ma.uid) 
JOIN groups og ON og.groupuid = mc.groupuid 
JOIN member m ON (m.memberuid = mc.memberuid) 
WHERE daterequested BETWEEN 
DATEADD(MONTH,-1,GETDATE()) 
AND 
GETDATE() 
AND isdeleted = 0 
GROUP BY datepart(wk,daterequested),daterequested 
--ORDER BY daterequested ASC 
) data 
GROUP BY data.week,data.weekstart,data.weekend,data.monthend