查询以获取入住率最高的房屋的房屋详细信息
有两个表房屋和租户历史记录用于计算最高入住率。
所以首先我要使用 datediff 函数来获取停留时间。
然后创建视图以使其充当虚拟表,并可以访问该列以获取最大值。
create view [dbo].[vWHouseStay]
as
select profile_id,
house_Id,
house_type,
bhk_details,Bed_type,
bed_count,
furnishing_type ,
DATEDIFF(MONTH,move_in_date,move_out_date) AS 'Total Length of stay'
from Tenancy_histories
join houses on tenancy_histories.house_Id = houses.house_id
我需要的是住所信息最多的住所。我怎么做?基本上,它只应退还最多[入住总时间]的房子。
表结构:
**Tenancy_histories**
Field Type Null Key Default
id int(11) NO PRI auto_increment
profile_id int(11) NO FK
house_id int(11) NO FK
move_in_date date NO
move_out_date date YES
rent int(11) NO
Bed_type varchar(255) YES
move_out_reason varchar(255) YES
**Houses**
Field Type Null Key Default
house_id int(11) NO PRI auto_increment
house_type varchar(255) YES
bhk_details varchar(255) YES
bed_count int(11) NO
furnishing_type varchar(255) YES
Beds_vacant int(11) NO
样本数据
house_id house_type bhk_details bed_count furnishing_type OccupancyDays
5 Independent 4 BHK 4 fully-furnished 443
7 Apartment 3 BHK 3 semifurnished 417
4 Apartment 2 BHK 2 fully-furnished 397
18 Independent 2 BHK 2 fully-furnished 358
16 Apartment 3 BHK 3 fully-furnished 324
19 Independent 3 BHK 3 fully-furnished 290
3 Apartment 3 BHK 6 fully-furnished 226
1 Apartment 3 BHK 5 unfurnished NULL
2 Apartment 3 BHK 3 unfurnished NULL
17 Independent 3 BHK 3 fully-furnished NULL
6 Apartment 3 BHK 3 semifurnished NULL
8 Apartment 2 BHK 4 fully-furnished NULL
样本数据[租赁历史]
id profile_id house_id move_in_date move_out_date rent Bed_type move_out_reason
242 1 5 2015-02-12 2016-04-30 7500 bed MOVE_OUT
243 2 2 2015-06-05 NULL 11000 room
244 3 4 2015-10-28 2016-11-28 12000 room RENT_CHANGE
245 4 1 2015-04-26 NULL 8000 bed
246 5 3 2015-05-15 2015-12-27 9000 bed MOVE_OUT
247 6 8 2015-12-25 NULL 10200 room
248 7 6 2015-11-20 NULL 6500 bed
249 8 7 2015-11-10 2016-12-31 7200 bed MOVE_OUT
250 9 9 2015-10-15 NULL 7500 bed
251 10 10 2015-06-20 NULL 7500 bed
252 11 19 2015-08-29 2016-06-14 8000 bed INTERNAL_TRANSFER
253 12 15 2015-02-24 NULL 11000 room
254 13 12 2015-02-25 NULL 12000 room
255 14 18 2016-01-07 2016-12-30 13500 room MOVE_OUT
256 15 13 2015-04-07 NULL 6500 bed
257 16 17 2015-04-23 NULL 6500 bed
258 17 14 2015-02-10 NULL 10500 room
259 18 16 2015-10-16 2016-09-04 8000 bed MOVE_OUT
260 19 20 2015-09-26 NULL 7500 bed
261 20 11 2015-09-30 NULL 9500 bed
答案 0 :(得分:0)
好像您想汇总所有租赁历史记录。这将是这样。也可以在视图中使用它。
;with cte as(
select
h.house_id
,h.house_type
,h.bhk_details
,h.bed_count
,h.furninshing_type
,OccupancyDays = sum(datediff(day,th.move_in_date,move_out_date))
from
Houses h
inner join
Tenancy_histories th on th.house_id = h.house_id)
group by
h.house_id
,h.house_type
,h.bhk_details
,h.bed_count
,h.furninshing_type
select TOP 1 --you can remove the TOP 1 to bring them all back
*
from cte
order by OccupancyDays desc