Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
774 views
in Technique[技术] by (71.8m points)

sql - Current month and last month data in single row

The following table has datatypes as follows:

ItemName varchar, Date Date, Amt varchar, status varchar

ItemName        Date        Amt     

    ABC       1/02/2012     500     
    ABC       8/03/2012     250     

Expected Result

ItemName    LastMonthAmt    CurrentMonthAmt

ABC          500             250

Please help me to write the query for this problem.

Thanks in advance.

What i have tried is as follows:

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]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use an aggregate function with a CASE expression similar to this:

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;

See SQL Fiddle with Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...