日期:2014-05-18  浏览次数:20432 次

这个inner join 怎么写?求高手指点!
表:product(商品信息) 字段:id,name
表:price(报价) 字段:pId,pDate,price
用 select id,name,pDate,price from [product] inner join [price] on id=pId where pDate>'[变量今天]' 得到的结果是
 商品1 名称1 日期1 价格1
 商品1 名称1 日期2 价格2
 商品1 名称1 日期3 价格3
 商品1 名称1 日期4 价格4
 …………………… 有多少个大于几天的报价就显示多少个
 商品2 名称2 日期1 价格1
 商品2 名称2 日期2 价格2
 商品2 名称2 日期3 价格3
 商品2 名称2 日期4 价格4
 ……………………有多少个大于几天的报价就显示多少个
 …………
请问要是先一个商品 只调取大于今天的最近的一个日期和报价怎么实现?
展示续如下
 商品1 名称1 日期1 价格1
 商品2 名称2 日期1 价格1
 商品3 名称3 日期1 价格1
 商品4 名称4 日期1 价格1
求高手指点!!!

------解决方案--------------------
SQL code

with t as
(select a.id,a.name,b.pDate,b.price,
row_number() over(partition by a.id order by b.pDate) rn 
from [product] a
inner join [price] b on a.id=b.pId 
where b.pDate>'[变量今天]'
)
select id,name,pDate,price
from t where rn=1

------解决方案--------------------
SQL code
select id,name,pDate,price from [product] 
inner join [price] on id=pId 
where datepart(dw,pDate)-datepart(dw,getdate())=1

------解决方案--------------------
SQL code

with test as
(
select a.id,a.name,b.pDate,b.price,
row_number() over( order by b.pDate) rownum
from project a 
inner join price b on a.id = b.pid
where b.pDate >'[变量今天]'
)
select top 1 * from test

------解决方案--------------------
SQL code


go
if object_id('tbl')is not null
drop table tbl
go
create table tbl(
[id] varchar(10),
[name] varchar(10),
pDate datetime,
price numeric(5,2)
)
go
insert tbl
select '1001','茄子','2012-01-25',2.5 union all
select '1001','茄子','2012-02-02',2.8 union all
select '1001','茄子','2012-03-06',2.2 union all
select '1002','萝卜','2012-02-24',1.5 union all
select '1002','萝卜','2012-02-19',1.2 union all
select '1002','萝卜','2012-03-01',1.3 union all
select '1003','西红柿','2012-01-25',3.2 union all
select '1003','西红柿','2012-02-25',3.0 union all
select '1003','西红柿','2012-03-06',2.9 union all
select '1004','土豆','2012-02-25',1.8 union all
select '1004','土豆','2012-02-28',1.5 union all
select '1004','土豆','2012-02-16',1.7


select * from tbl a
where pDate=(select max(pdate) from tbl b where pdate<=getdate() 
and a.[id]=b.[id]) order by [id] asc
/*
id  name  pDate  price 
1001    茄子    2012-03-06 00:00:00.000    2.20
1002    萝卜    2012-03-01 00:00:00.000    1.30
1003    西红柿    2012-03-06 00:00:00.000    2.90
1004    土豆    2012-02-28 00:00:00.000    1.50

*/