如何取最低的两个价格?
如表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
---------- ---------- ------------
中亚饭店 标房 300.00
中亚饭店 高级房 400.00
国际饭店 标房 1300.00
国际饭店 高级房 1400.00
(4 row(s) affected)
[解决办法]
select * from HotelPrice as A
where (select count(*) from HotelPrice 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 a where (select count(*) from T b where b.hotel=a.hotel and b.saleprice <=a.saleprice) <=2
当在别名a表中查到saleprice为300时,也就是a.saleprice=300,select count(*) from T b where b.hotel=a.hotel and b.saleprice <=a.saleprice中查到结果为1,1 <2,所以a.saleprice=300的条件满足.同理a.saleprice=400也满足.a.saleprice=500/600不满足