日期:2014-05-17  浏览次数:20801 次

sql 语句 如何取最近价格?
记录如下:
表A
id         商品编号     价格
 1            001        6.00
 2            002        5.00
 3            001        7.00

问:用SQL 语句如何根据最大ID,取同一商品编号 的最近价格?(如商品编号 001 最大ID 3 ,相应价格 7.00)              
------最佳解决方案--------------------
----------------------------
-- Author  :TravyLee(物是人非事事休,欲语泪先流!)
-- Date    :2012-12-06 15:37:44
-- Version:

--      Microsoft SQL Server 2012 - 11.0.2100.60 (Intel X86) 

-- Feb 10 2012 19:13:17 

-- Copyright (c) Microsoft Corporation

-- Enterprise Edition: Core-based Licensing on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)

--
----------------------------
--> 测试数据:[表A]
if object_id('[表A]') is not null drop table [表A]
go 
create table [表A]([id] int,[商品编号] varchar(3),[价格] numeric(3,2))
insert [表A]
select 1,'001',6.00 union all
select 2,'002',5.00 union all
select 3,'001',7.00

go


select 
*
from [表A] a where a.id=(select max(id) from [表A] b where a.商品编号=b.商品编号)
/*
id          商品编号 价格
----------- ---- ---------------------------------------
2           002  5.00
3           001  7.00

(2 行受影响)


*/


------其他解决方案--------------------
select *
from tb a
where exists (select 1 from (select max(id)id, 商品编号 from tb group by  商品编号) b where a.id=b.id and a. 商品编号=b. 商品编号)
------其他解决方案--------------------

CREATE TABLE [表A]
    (
      [id] INT ,
      [商品编号] VARCHAR(3) ,
      [价格] NUMERIC(3, 2)
    )
INSERT  [表A]
        SELECT  1 ,
                '001' ,
                6.00
        UNION ALL
        SELECT  2 ,
                '002' ,
                5.00