只是一個簡單的想法,爲您提供有關Pivoting的知識。我用我的日期格式替換了它,但最好使用動態查詢進行旋轉。
CREATE TABLE [dbo].[tblTest](
[Item] [varchar](50) NOT NULL,
[Count] [int] NOT NULL,
[Date] [date] NOT NULL
)
insert into tblTest values('item1', 10, '01MAR14')
insert into tblTest values('item1', 5 , '02MAR14')
insert into tblTest values('Item2', 5 , '01MAR14')
insert into tblTest values('item3', 12, '03MAR14')
insert into tblTest values('item2', 12, '04MAR14')
insert into tblTest values('item3', 2 , '05MAR14')
insert into tblTest values('item1', 3 , '05MAR14')
SELECT Item, IsNull([2014-03-05], 0) as [2014-03-05], Isnull([2014-03-04], 0) [2014-03-04], IsNull([2014-03-03],0) [2014-03-03], ISNULL([2014-03-02], 0) as 'Before[2014-03-01]'
FROM (
SELECT
Item, case when [Date] < '2014-03-03' then '2014-03-02' else [DATE] end as [Date], [Count]
FROM tblTest
) AS s
PIVOT
(
sum([Count])
FOR [Date] IN ([2014-03-05],[2014-03-04],[2014-03-03], [2014-03-02])
)AS pivotTable
感謝sna2stha – Wilz