假设我有一个名为
Building_Rooms
的表,其中包含以下列:
ID
- 只是一个普通的 ID Address
- nvarchar 街道地址RoomType
- nvarchar 房间类型(例如,bedroom
、kitchen
、bathroom
等)(我知道这看起来像是糟糕的数据库设计,但不用担心。我正在尝试提出最简单、易于理解的说明性示例。)
如何获取表中
every
RoomType
值存在的不同 Address
值?
例如,如果表中同时包含办公楼和住宅楼,则结果不会有
bedroom
,因为大多数办公楼没有卧室,所以不会有 boardroom
,因为大多数住宅没有卧室会议室等。我们可能期望结果只不过是 bathroom
,因为这将是表中每个 RoomType
值都存在的唯一 Address
值。
可重现的示例代码:
create table [Building_RoomTypes]
(
[ID] UNIQUEIDENTIFIER NOT NULL PRIMARY KEY DEFAULT NEWID(),
[Address] varchar(255),
[RoomType] varchar(255)
)
insert into [Building_RoomTypes]
values (NEWID(), '100 Wall Street', 'office'),
(NEWID(), '100 Wall Street', 'office'),
(NEWID(), '100 Wall Street', 'office'),
(NEWID(), '100 Wall Street', 'office'),
(NEWID(), '100 Wall Street', 'boardroom'),
(NEWID(), '100 Wall Street', 'kitchen'),
(NEWID(), '100 Wall Street', 'lobby'),
(NEWID(), '100 Wall Street', 'bathroom'),
(NEWID(), '100 Wall Street', 'bathroom'),
(NEWID(), '54 Residential Road', 'bedroom'),
(NEWID(), '54 Residential Road', 'bedroom'),
(NEWID(), '54 Residential Road', 'bedroom'),
(NEWID(), '54 Residential Road', 'kitchen'),
(NEWID(), '54 Residential Road', 'bathroom'),
(NEWID(), '54 Residential Road', 'living room'),
(NEWID(), '890 Downtown Avenue - Unit 1', 'bedroom'),
(NEWID(), '890 Downtown Avenue - Unit 1', 'kitchen'),
(NEWID(), '890 Downtown Avenue - Unit 1', 'bathroom')
如果成功查询所有不同
RoomType
值存在的所有不同 Address
值,则预期结果:
RoomType
--------
bathroom
kitchen
SQL Server 版本号:14.0.2065.1
我真的不喜欢这个,但我还没有看到更好的选择。
with ranked as (
select rt.roomtype, rank() over (order by count(address) desc) rk
from (
select distinct roomtype, address from building_roomtypes
) rt
group by rt.roomtype
)
select roomtype
from ranked
where rk = 1
但它至少有效,前提是至少有一种房型符合标准。否则,它将显示最接近的房间类型。
在这里查看: