34,588
社区成员
发帖
与我相关
我的任务
分享
CREATE TABLE [dbo].[users](
[id] [int] IDENTITY(1,1) NOT NULL,
[userid] [int] NOT NULL,
[score] [int] NOT NULL,
[createtime] [datetime] NOT NULL,
CONSTRAINT [PK_users] 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
ALTER TABLE [dbo].[users] ADD CONSTRAINT [DF_users_userid] DEFAULT ((0)) FOR [userid]
GO
ALTER TABLE [dbo].[users] ADD CONSTRAINT [DF_users_score] DEFAULT ((0)) FOR [score]
GO
ALTER TABLE [dbo].[users] ADD CONSTRAINT [DF_users_createtime] DEFAULT (getdate()) FOR [createtime]
GO
SELECT TOP 10
[UserID] ,
SUM([Score]) score
FROM [users]
GROUP BY UserID
ORDER BY Score DESC
-->try
SELECT top 10 [UserID] into #tmp
FROM [users] group by UserID
select [UserID], sum([Score]) Score from [users]
where [UserID] in (select t.[UserID] from #tmp t)
order by Score desc
--drop table #tmp
-->try
select t.[UserID],sum(t.[Score]) Score
from
(
SELECT top 10 [UserID],[Score]
FROM [users]
group by UserID
order by Score desc
) t