每个类别仅显示2个软件

时间:2014-08-19 23:22:12

标签: mysql sql sql-server oracle postgresql

我有一个表软件(id_software,software_name,category)

每个类别只显示2个软件的SQL查询是什么?

例如我想得到:

 |id_software | software_name | category|
-+------------+---------------+---------+-
 |          1 | Photoshop     | 5       |
 |          2 | illustrator   | 5       |
 |          3 | Firefox       | 1       |
 |          4 | I.E           | 1       |
-+--------------------------------------+-

2 个答案:

答案 0 :(得分:1)

select * from
(select *
from table1 n
where
( select count(*)
from table1 m
where n.categorie = m.categorie
and n.id_software <= m.id_software) <= 2
order by n.id_software, n.id_software desc) as tn

来源:http://mindbuffer.wordpress.com/2013/07/09/mysql-get-the-top-2-rows-for-each-category-with-certain-condition/

答案 1 :(得分:1)

您可以使用row_number函数。

SELECT *
FROM 
     (SELECT 
          Category,
          id_software,
          software_name,
          [Nth_Software] = ROW_NUMBER() OVER (Partition by Category ORDER BY Id_software)
     FROM
          table
      ) T
WHERE
     T.Nth_Software <=2

这为您提供了基于每个类别的softwareId的前两个软件条目。