根据在两列上完成的计算,返回MAX值的所有行

时间:2017-10-01 13:28:36

标签: sql sql-server max correlated-subquery

我有一张名为' Houses'其中包含字段' house_id',' house_type',' bhk_detail',' bed_count',' furnishing_type',&# 39; Beds_vacant&#39 ;.现在我需要写一个查询,以获得最高入住率的房子的房子细节bed_count - bed_vacant。我试过这样的事情:

SELECT hs.house_id, hs.house_type , hs.bhk_details, hs.bed_count , hs.furnishing_type, hs.Beds_vacant,
       max(hs.bed_count - hs.Beds_vacant
FROM Houses as hs 
GROUP BY hs.house_id, hs.house_type, hs.bhk_details, hs.bed_count, hs.furnishing_type, hs.Beds_vacant 
HAVING MAX(hs.bed_count - hs.Beds_vacant)IN (SELECT max(hs.bed_count - hs.Beds_vacant) FROM Houses as hs) 

该查询对我有用,但我想知道我们是否可以更精确地编写

1 个答案:

答案 0 :(得分:3)

我认为最简单的方法是top 1 with ties

select top (1) with ties h.*
from Houses h
order by (h.bed_count - h.beds_vacant) desc;
相关问题