如何连接多个SQL表并获取每个表的计数

时间:2018-01-22 20:08:12

标签: sql-server join aggregate

我需要一个T-SQL查询,它可以连接多个表,但也返回每个表的计数。我知道如何单独完成每个部分但不能让它们一起工作。

鉴于此SQL架构:

CREATE TABLE [House] 
(
    [Id] INT IDENTITY (1, 1) NOT NULL,
    [Price] DECIMAL (5, 2) NOT NULL,
);

CREATE TABLE [Floor] 
(
    [Id] INT IDENTITY (1, 1) NOT NULL,
    [HouseId] INT NOT NULL,

    CONSTRAINT [FK_Floor_HouseId] 
        FOREIGN KEY ([HouseId]) REFERENCES [House] ([Id])
);

CREATE TABLE [Room] 
(
    [Id] INT IDENTITY (1, 1) NOT NULL,
    [FloorId] INT NOT NULL,
    [Type] VARCHAR,

    CONSTRAINT [FK_Room_FloorId] 
        FOREIGN KEY ([FloorId]) REFERENCES [Floor] ([Id])
);

我需要一个SQL查询,它将返回包含以下信息的单个列表,我知道查询可能会很混乱。

  • [豪斯]。[ID]
  • [豪斯]。[参考价格]
  • [FloorCount] - 每个房子的总楼层数
  • [RoomCount] - 每个房子的房间总数
  • [BedroomCount] - [Type] ='Bedroom'
  • 的房间数量

2 个答案:

答案 0 :(得分:2)

这是一个聚合查询。它似乎并不特别复杂:

select f.houseid,
       count(distinct f.id) as numfloors,
       count(*) as numrooms,
       sum(case when type = 'bedroom' then 1 else 0 end) as numbedrooms
from floor f join
     room r
     on f.id = r.floorid
group by f.houseid;

答案 1 :(得分:1)

可能有更好的方法,但我通过分组房屋ID并使用max函数来获得价格来解决它。有多行,都有相同的价格,但我只需要获得其中一行。

SELECT [House].[Id],
       MAX([House].[Price]),
       COUNT(distinct [Floor].[Id]) AS [FloorCount],
       COUNT(distinct [Room].[Id]) as [TotalRoomCount],
       SUM(CASE WHEN [Type] = 'Bedroom' THEN 1 ELSE 0 END) AS [BedroomCount]
FROM [House]
LEFT JOIN [Floor] ON [Floor].[HouseId] = [House].[Id]
LEFT JOIN [Room] on [Room].[FloorId] = [Floor].[Id]
GROUP BY [House].[Id];