【问题标题】:Show only 2 softwares for each category每个类别仅显示 2 个软件
【发布时间】:2014-10-13 05:01:36
【问题描述】:

我有一个表软件(id_software、software_name、类别)

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

例如我想得到:

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

【问题讨论】:

  • 您可以为此发布您的示例数据吗?
  • 你好 Saechel,表格软件仅包含 3 个字段(id_software、software_name、类别),我只想为每个类别显示 2 行
  • quel SQL 再来一次? [mysql|sql|sql-sewer|oracle|postgresql]
  • @wildplasser,对不起? je n'ai pas compris j'ai mis tout ces tags pour plus de visibilité, de toute façon la syntaxe on s'en fou j'ai besoin de connaitre le raisonnement
  • Bien sur!:[简而言之]你的问题太宽泛了。还:表现出一些努力;因为它看起来微不足道。

标签: mysql sql sql-server oracle postgresql


【解决方案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/

【讨论】:

  • 如果这个对你有用,你为什么不在这个答案中给出你接受的分数而不是另一个?
【解决方案2】:

您可以为此使用 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 为您提供前两个软件条目。

【讨论】:

  • 您应该补充说这只是 SQL Server/T-SQL 语法([...] 引用和列中的“赋值”运算符)
猜你喜欢
  • 1970-01-01
  • 2014-11-18
  • 2021-01-02
  • 2016-10-07
  • 1970-01-01
  • 2018-09-03
  • 1970-01-01
  • 1970-01-01
  • 2017-06-14
相关资源
最近更新 更多