大家好,向高手请教一个问题。
表Products表中有:ProductID,ProductName,AccountDate,ProductPrice字段。其中,ProductID,ProductName为Varchar类型,AccountDate为yyyy-mm的Varchar类型,ProductPrice为decimal类型。
现要取出记录(数据不一定准确,仅供参考):
产品编号    产品名称   统计年月     价格       同比
NP1001    劳力士        2009年9月  1234.13    2.24%
NP1002    TCL手机       2009年8月  1566.12     
NP1003    联想笔记本    2008年9月  5434.23     2.22%
NP1004    华硕电脑      2009年6月  3434.13     2.21%
NP1005    劳力士5       2009年5月  10234.00      2.20%
NP1006    劳力士6       2009年4月  234.13      4.00%
同比:(该月的价格-上个月的价格)/上个月的价格*100%;
如果上个月的价格为空,则同比显示为空,否则同比保留两位小数。
查询出的价格也是保留两位小数。
统计月份按照YYYY年MM月的格式显示。请问这个查询功能用一条SQL语句怎么实现?

解决方案 »

  1.   

    select m.ProductID,m.ProductName,m.AccountDate,m.ProductPrice,
           case when n.ProductPrice is null then '' 
                else cast(cast((m.ProductPrice - n.ProductPrice)*100/n.ProductPrice as decimal(18,2)) as varchar)
           end 同比
    from Products m left join Products n
    on m.ProductID = n.ProductID and m.ProductName = n.ProductName and datediff(mm,n.AccountDate+'-01',m.AccountDate+'-01') = 1
      

  2.   

    左連接,條件為日期相差一個月declare @t table(a char(1) ,b datetime,c decimal)
    insert into @t
    select 'A','2009-08-01',2 union all
    select 'A','2009-09-01',3 union all
    select 'B','2009-05-01',4 union all
    select 'B','2009-06-01',7 union all
    select 'B','2009-07-01',8 union all
    select 'C','2009-09-01',6select t.*,v.c/t.c as Result
    from @t t
    left join @t v
    on t.a=v.a
    and t.b<v.b
    and datediff(mm,t.b,v.b)=1a    b                       c                                       Result
    ---- ----------------------- --------------------------------------- ---------------------------------------
    A    2009-08-01 00:00:00.000 2                                       1.5000000000000000000
    A    2009-09-01 00:00:00.000 3                                       NULL
    B    2009-05-01 00:00:00.000 4                                       1.7500000000000000000
    B    2009-06-01 00:00:00.000 7                                       1.1428571428571428571
    B    2009-07-01 00:00:00.000 8                                       NULL
    C    2009-09-01 00:00:00.000 6                                       NULL