-4
下表具有數據類型如下:當月和上月數據
ITEMNAME VARCHAR,日期日期,金額爲varchar,狀態VARCHAR
ItemName Date Amt
ABC 1/02/2012 500
ABC 8/03/2012 250
預期結果
ItemName LastMonthAmt CurrentMonthAmt
ABC 500 250
請幫我寫下這個問題的查詢。
在此先感謝。
我曾嘗試如下:
declare @T table
(
id varchar(2),
[Date] datetime,
[Amt] varchar(5),
[Status] varchar(5)
)
insert into @T
select '01', '1/02/12', '125', 'LM' union all
--select '01', '1/02/12', '200', 'Exit' union all
select '01', '2/02/12', '250', 'CM' union all
--select '01', '2/02/12', '150', 'CM' union all
select '02', '1/02/12', '300', 'LM' union all
--select '02', '1/02/12', '350', 'CM' union all
--select '02', '2/02/12', '220', 'LM' union all
select '02', '2/02/12', '140', 'CM'
select id,
--convert(varchar(8), [Date], 1) as [Date],
[Amt] as [CM],
[Amt] as [LM]
from
(
select distinct id,
[Amt],
row_number() over(partition by id order by [Date] asc) as rn1,
row_number() over(partition by id order by [Date] desc) as rn2
from @T
) as T
where T.rn1 = 1 or
T.rn2 = 1
group by id, [Amt]
[你嘗試過什麼](http://www.whathaveyoutried.com) – Kermit 2013-03-08 15:18:56
如果你在哪裏顯示你已經嘗試過,人們會更能夠幫助你,因爲堆棧溢出是不是人們爲您編寫代碼的網站,而是幫助您解決問題。 – 2013-03-08 15:26:54