SQL - 选择编号最大的前10行(计数)

时间:2015-08-09 22:27:55

标签: sql sql-server

您好我有一个充满了球员记录的数据库,他们的比赛统计数据。

示例:

Database example

(数字表示在比赛中得分)

我要做的就是选择能够在赛季中获得大部分进球的前X球员。

我正在尝试这样的事情,但我认为必须有另一个选择计数(数字)或其他东西。

  SELECT TOP 10 [playerID]
      ,[number]
      ,[league]
      ,[yearID]
      ,[YellowCard]
      ,[RedCard]
  FROM [ms4033].[dbo].[Shooter]
  where yearID=28 AND league=4
  group by playerID

感谢您的时间: - )

3 个答案:

答案 0 :(得分:2)

select top 10 
 t.[playerID]
,t.totalgoals
,s.[league]
,s.[yearID]
,s.[YellowCard]
,s.[RedCard] from (
SELECT -- TOP 10 
   [playerID]
  ,sum([number]) as totalgoals
  ,[league]
  ,[yearID]
  -- ,[YellowCard]
  -- ,[RedCard]
FROM [ms4033].[dbo].[Shooter]
where yearID=28 AND league=4
group by playerID,[league],[yearID]) t
join [ms4033].[dbo].[Shooter] s on t.playerid = s.playerid
order by totalgoals desc

您可以对内部查询中的总目标进行计算,并命令它选择前10名玩家。

答案 1 :(得分:2)

您需要SUM数字字段并按此顺序排序;

 SELECT TOP 10 
      playerID, 
      SUM([number]) as goals,
      [league],
      [yearID],
      SUM([YellowCard]) as YellowCards,
      SUM([RedCard]) as RedCards,
  FROM [ms4033].[dbo].[Shooter]
  WHERE yearID=28 AND league=4
  GROUP BY playerID, league, yearID
  ORDER BY goals DESC

答案 2 :(得分:0)

这是你的意思吗?

 SELECT TOP 10 [playerID]
      ,count([number])
  FROM [ms4033].[dbo].[Shooter]
  where yearID=28 AND league=4
  group by playerID
  Order by count(number) desc