缥缈止盈
@dotNetDR_:
哎.一瓶可乐过后.睡不着郁闷.只好做做题了
希望对你有帮助.
--建表CREATE TABLE #temp_SalesReport ( [Month] datetime not null, [Amount] money not null)DECLARE @MonthDiffer int --月份差SET @MonthDiffer = 0DECLARE @Amount moneySET @Amount = 100.00DECLARE @StartMonth datetime --开始的月份DECLARE @MenthCOunt int --计算月数 范围{ 1 ... 12 }SET @StartMonth = CAST('2011-01-01' AS datetime)SET @MenthCOunt = 12 --模拟一年的销售DECLARE @MonthDate datetimeSET @MonthDate = DATEADD(dd, -day(@StartMonth) + 1, @StartMonth)--Debug--SELECT @MonthDate--插数据WHILE (@MonthDiffer < @MenthCOunt)BEGIN INSERT INTO #temp_SalesReport ( [Month], [Amount] ) VALUES ( @StartMonth, @Amount ) SET @Amount = @Amount + 100.00 SET @StartMonth = DATEADD(dd, 1, @StartMonth) SET @MonthDiffer = DATEDIFF(mm, @MonthDate, @StartMonth) --print @MonthDifferEND--Debug--SELECT * FROM #temp_SalesReport--DELETE FROM #temp_SalesReport--实现,先计算出月份和第几周;WITH CTE_1 AS ( SELECT (DATENAME(dd, [Month]) + 6) / 7 [WeekOfMonth], -- 加6 是 -1 + 7来的,这列是获取当月的周编号 MONTH([Month]) [MonthForNum], -- 获取月份 --[Month], --Debug时可以取消看结果 [Amount] FROM [#temp_SalesReport]) --select * from CTE_1 --Debug,CTE_2 AS ( SELECT [MonthForNum], [WeekOfMonth], [Amount] FROM CTE_1)--SELECT * FROM CTE_2 --Debug/* Debug (最终结果)SELECT MonthForNum, WeekOfMonth, SUM(Amount) [AmountTotal] FROM CTE_2 GROUP BY MonthForNum, WeekOfMonthORDER BY MonthForNum, WeekOfMonth*/--行转列后的最终结果SELECT CAST(MonthForNum AS NVARCHAR(2)) + N'月份' [月份], [1] [第一周], [2] [第二周], [3] [第三周], [4] [第四周], CASE WHEN [5] is null THEN CAST(0.00 AS money) ELSE [5] END [第五周]FROM ( SELECT * FROM CTE_2 GROUP BY MonthForNum, WeekOfMonth, Amount) [SourceTable]PIVOT ( SUM([Amount]) FOR [WeekOfMonth] IN ( [1], [2], [3], [4], [5] )) [PivotTable]
效果图
行转列参考http://www.cnblogs.com/highend/archive/2011/07/15/how_to_using_pivot_and_unpivot.html