-4

次の表には、次のようなデータ型があります。

ItemName varchar、Date Date、Amt varchar、status 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]
4

1 に答える 1

3

CASE次のような式で集計関数を使用できます。

select itemname,
  sum(case when month(date) = month(getdate()) -1 then amt else 0 end) LastMonthAmt,
  sum(case when month(date) = month(getdate()) then amt else 0 end) CurrentMonthAmt
from yourtable
group by itemname;

デモで SQL Fiddle を参照してください

于 2013-03-08T15:23:16.247 に答える