【问题标题】:Current month and last month data in single row单行当月和上月数据
【发布时间】:2013-02-24 04:33:28
【问题描述】:

下表的数据类型如下:

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]

【问题讨论】:

  • 如果你在哪里展示你尝试过的东西,人们会更能帮助你,因为 Stack Overflow 不是人们为你编写代码的网站,而是帮助你解决问题的地方。

标签: sql sql-server sql-server-2008


【解决方案1】:

您可以使用带有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 with Demo

【讨论】:

    猜你喜欢
    • 2017-10-26
    • 1970-01-01
    • 2023-02-23
    • 2019-06-27
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-05-06
    相关资源
    最近更新 更多