我希望每个区域只有一行,在给定的日期范围内动态生成周列。这是我目前的输出。
Shipment Region WeekNumber territory AccountName
1 BRK Week 1 March 2014 0002 RRTS
3 BRK Week 2 March 2014 0002 RRTS
1 BRK Week 3 March 2014 0002 RRTS
1 BRK Week 5 March 2014 0002 RRTS
1 DED Week 3 March 2014 0002 RRTS
14 EXP Week 1 March 2014 0002 RRTS
25 EXP Week 2 March 2014 0002 RRTS
15 EXP Week 3 March 2014 0002 RRTS
20 EXP Week 4 March 2014 0002 RRTS
3 EXP Week 5 March 2014 0002 RRTS
14 LTL Week 1 March 2014 0002 RRTS
19 LTL Week 2 March 2014 0002 RRTS
查询
SELECT
count(*) as Count, p.regionid,
CASE WHEN DATEPART(day,p.prodate) < 8 THEN CAST('Week 1 ' AS VARCHAR(20)) + DATENAME(MONTH, p.prodate) + CAST(' ' AS VARCHAR(4)) + CAST(YEAR(p.prodate) AS VARCHAR(4))
--convert(nvarchar,DATEPART(month,p.prodate))
WHEN DATEPART(day,p.prodate) < 15 then CAST('Week 2 ' AS VARCHAR(20)) + DATENAME(MONTH, p.prodate) + CAST(' ' AS VARCHAR(4)) + CAST(YEAR(p.prodate) AS VARCHAR(4))
--+ CAST(YEAR(p.prodate) AS VARCHAR(4)) + DATENAME(MONTH, p.prodate)
WHEN DATEPART(day,p.prodate) < 22 then CAST('Week 3 ' AS VARCHAR(20)) + DATENAME(MONTH, p.prodate) + CAST(' ' AS VARCHAR(4)) + CAST(YEAR(p.prodate) AS VARCHAR(4))
WHEN DATEPART(day,p.prodate) < 29 then CAST('Week 4 ' AS VARCHAR(20)) + DATENAME(MONTH, p.prodate) + CAST(' ' AS VARCHAR(4)) + CAST(YEAR(p.prodate) AS VARCHAR(4))
ELSE CAST('Week 5 ' AS VARCHAR(20))+ DATENAME(MONTH, p.prodate) + CAST(' ' AS VARCHAR(4)) + CAST(YEAR(p.prodate) AS VARCHAR(4))
END as WeekNumber,a.territory,'rrts' from pros p inner join GTS_Account a on a.locationGTSNo = p.BillToCustNo
where a.account like '%rrts%' and
p.prodate between '2014-01-01' and '2014-02-28' group by
CASE WHEN DATEPART(day,p.prodate) < 8 THEN CAST('Week 1 ' AS VARCHAR(20)) + DATENAME(MONTH, p.prodate) + CAST(' ' AS VARCHAR(4)) + CAST(YEAR(p.prodate) AS VARCHAR(4))
WHEN DATEPART(day,p.prodate) < 15 then CAST('Week 2 ' AS VARCHAR(20)) + DATENAME(MONTH, p.prodate) + CAST(' ' AS VARCHAR(4)) + CAST(YEAR(p.prodate) AS VARCHAR(4))
WHEN DATEPART(day,p.prodate) < 22 then CAST('Week 3 ' AS VARCHAR(20)) + DATENAME(MONTH, p.prodate) + CAST(' ' AS VARCHAR(4)) + CAST(YEAR(p.prodate) AS VARCHAR(4))
WHEN DATEPART(day,p.prodate) < 29 then CAST('Week 4 ' AS VARCHAR(20)) + DATENAME(MONTH, p.prodate) + CAST(' ' AS VARCHAR(4)) + CAST(YEAR(p.prodate) AS VARCHAR(4))
ELSE CAST('Week 5 ' AS VARCHAR(20)) + DATENAME(MONTH, p.prodate) + CAST(' ' AS VARCHAR(4)) + CAST(YEAR(p.prodate) AS VARCHAR(4))
END
,a.territory, p.regionid
order by p.regionid, weeknumber
所需的输出是:
Region Territory Week1 Week2 Week3 Week4 Week5 Week6
BRK 2 4 6 8 10 5 4
DED 2 7 5 4 7 7 2
EXP 2 1 1 2 4 5 6
谢谢! 我正在使用sql server 2008