我有一个表软件(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 |
-+--------------------------------------+-
答案 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
答案 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的前两个软件条目。