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

如何取最低的两个价格?
如表HotelPrice中有这样几条记录:

hotel                 room               saleprice
中亚饭店           标房    300.00
中亚饭店     高级房             400.00
中亚饭店     豪华房             500.00
中亚饭店     套房    600.00
国际饭店           标房    1300.00
国际饭店     高级房             1400.00
国际饭店     豪华房             1500.00
国际饭店     套房    1600.00

想要的结果是只取每个酒店最低的两个价格,如下:
hotel                 room               saleprice
中亚饭店           标房    300.00
中亚饭店     高级房             400.00
国际饭店           标房    1300.00
国际饭店     高级房             1400.00

该怎么写呢?

------解决方案--------------------
create table T(hotel varchar(20),room varchar(20),saleprice dec(12,2))
insert T select '中亚饭店 ', '标房 ',300.00
union all select '中亚饭店 ', '高级房 ',400.00
union all select '中亚饭店 ', '豪华房 ',500.00
union all select '中亚饭店 ', '套房 ',600.00
union all select '国际饭店 ', '标房 ',1300.00
union all select '国际饭店 ', '高级房 ',1400.00
union all select '国际饭店 ', '豪华房 ',1500.00
union all select '国际饭店 ', '套房 ',1600.00

select * from T a where (select count(*) from T where hotel=a.hotel and saleprice <=a.saleprice) <=2

drop table T
------解决方案--------------------
SELECT *
FROM HotelPrice p
WHERE
(SELECT COUNT(*)
FROM HotelPrice px
WHERE px.hotel=p.hotel
AND px.saleprice <=p.saleprice)=2
ORDER BY hotel, saleprice
------解决方案--------------------
create table T(hotel nvarchar(10), room nvarchar(10), saleprice decimal(10,2))
insert T select '中亚饭店 ', '标房 ', 300.00
union all select '中亚饭店 ', '高级房 ', 400.00
union all select '中亚饭店 ', '豪华房 ', 500.00
union all select '中亚饭店 ', '套房 ', 600.00
union all select '国际饭店 ', '标房 ', 1300.00
union all select '国际饭店 ', '高级房 ', 1400.00
union all select '国际饭店 ', '豪华房 ', 1500.00
union all select '国际饭店 ', '套房 ', 1600.00

select * from T as A
where (select count(*) from T where hotel=A.hotel and saleprice <A.saleprice) <2
------解决方案--------------------
create table T(hotel nvarchar(10), room nvarchar(10), saleprice decimal(10,2))
insert T select '中亚饭店 ', '标房 ', 300.00
union all select '中亚饭店 ', '高级房 ', 400.00
union all select '中亚饭店 ', '豪华房 ', 500.00
union all select '中亚饭店 ', '套房 ', 600.00
union all select '国际饭店 ', '标房 ', 1300.00
union all select '国际饭店 ', '高级房 ', 1400.00
union all select '国际饭店 ', '豪华房 ', 1500.00
union all select '国际饭店 ', '套房 ', 1600.00

select * from T as A
where (select count(*) from T where hotel=A.hotel and saleprice <A.saleprice) <2

--result
hotel room saleprice