如何在sql查询中获取星期格式化的字符串

时间:2015-05-11 22:57:38

标签: sql sql-server

我有以下SQL查询(sql server 2008):

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

有任何线索吗?

1 个答案:

答案 0 :(得分: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