Sql在每个分类中获得前2个结果

时间:2014-09-19 05:54:12

标签: sql sql-server sql-server-2008

嗨,我是sql的新手,遇到了问题。

以下是我桌子的样本。这不是确切的表格,而是我想要实现的样本

   Name Classification Hits
    A      A1             2
    A      A2             3
    A      A3             4
    A      A4             8
    A      A5             9
    B      B1             9
    B      B2             3
    B      B3             4
    B      B4             8
    B      B5             9
    c      c1             8
    c      c2             9
    c      c3             4
    c      c4             8
    c      c5             9
    ...

我正在寻找基于热门歌曲的结果。例如

Name Classification Hits
A      A4             8
A      A5             9
B      B1             9
B      B5             9
c      c2             9
c      c5             9

我试过这个查询

SELECT  TOP (2) Name , Classification , Hits
FROM   Table4
Group By  Name , Classification , Hits
Order By Hits

但我只得到两个价值观。我在这做错了什么建议?

3 个答案:

答案 0 :(得分:2)

您可以使用具有Row_Number()功能

的CTE
;WITH CTE AS(
  SELECT Name,
         Classification,
         Hits,
         Row_Number() OVER(Partition by name ORDER BY Hits DESC) AS RowNum
  FROM Table4
  )

SELECT Name,
       Classification,
       Hits
FROM CTE
WHERE RowNum <= 2
ORDER BY Name, Hits

SQL FIDDLE DEMO

答案 1 :(得分:0)

我正在从记忆中工作,所以我不确定语法,并且可能有更有效的方法来做到这一点,但是你想要做类似的事情

;with rawdata as (
   select Name, Classification, Hits, 
          Row_number() over (partition by Name order by Hits desc) as x
)
select Name, Classification, Hits from rawdata where x < 3

答案 2 :(得分:0)

这也有效。不使用ROW_NUMBER()。

Select a.* from MyTable as M1
Cross apply
(
    Select  top 2   * from Mytable m2
    where m1.name = m2.name
    order by m2.Hits desc
)as a
where a.Classification = m1.Classification

Fiddle Demo

但我不了解表现。