Sql 每个分支机构的前三项记录

Sql 每个分支机构的前三项记录,sql,greatest-n-per-group,Sql,Greatest N Per Group,我需要为公司每个分支机构的前三名recordcount和sum编写查询,我有分支机构客户和合同表首先,创建如下表: CREATE TABLE [dbo].[Branches]( [Id] [int] NOT NULL, [CompanyId] [int] NULL, [Something] [int] NULL, CONSTRAINT [PK_Table_5] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX

我需要为公司每个分支机构的前三名recordcount和sum编写查询,我有分支机构客户和合同表

首先,创建如下表:

CREATE TABLE [dbo].[Branches](
    [Id] [int] NOT NULL,
    [CompanyId] [int] NULL,
    [Something] [int] NULL,
 CONSTRAINT [PK_Table_5] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SELECT result.Companyid, SUM(result.Something) [Sum], (SELECT COUNT(*) FROM Branches WHERE CompanyId = result.companyid) AS [Count]
    FROM (
        SELECT companyid, Something, Rank() 
          OVER (PARTITION BY CompanyId
                ORDER BY id DESC ) AS Rank
        FROM Branches
        ) result WHERE Rank <= 3
GROUP BY CompanyId
然后,在其中插入一些数据:

INSERT [dbo].[Branches] ([Id], [CompanyId], [Something]) VALUES (1, 1, 10)
GO
INSERT [dbo].[Branches] ([Id], [CompanyId], [Something]) VALUES (2, 1, 15)
GO
INSERT [dbo].[Branches] ([Id], [CompanyId], [Something]) VALUES (3, 1, 20)
GO
INSERT [dbo].[Branches] ([Id], [CompanyId], [Something]) VALUES (4, 1, 25)
GO
INSERT [dbo].[Branches] ([Id], [CompanyId], [Something]) VALUES (5, 1, 22)
GO
INSERT [dbo].[Branches] ([Id], [CompanyId], [Something]) VALUES (6, 2, 50)
GO
INSERT [dbo].[Branches] ([Id], [CompanyId], [Something]) VALUES (7, 2, 32)
GO
INSERT [dbo].[Branches] ([Id], [CompanyId], [Something]) VALUES (8, 2, 30)
GO
INSERT [dbo].[Branches] ([Id], [CompanyId], [Something]) VALUES (9, 2, 10)
GO
最后,您的查询将如下所示:

CREATE TABLE [dbo].[Branches](
    [Id] [int] NOT NULL,
    [CompanyId] [int] NULL,
    [Something] [int] NULL,
 CONSTRAINT [PK_Table_5] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SELECT result.Companyid, SUM(result.Something) [Sum], (SELECT COUNT(*) FROM Branches WHERE CompanyId = result.companyid) AS [Count]
    FROM (
        SELECT companyid, Something, Rank() 
          OVER (PARTITION BY CompanyId
                ORDER BY id DESC ) AS Rank
        FROM Branches
        ) result WHERE Rank <= 3
GROUP BY CompanyId
模式:

第一个数据:

结果:


请参见此处:发送您的表架构和示例数据以及您期望的结果。您的数据库是什么?