简体   繁体   English

SQL查询为列中具有相同值的每个条目返回3行?

[英]Sql Query to return 3 rows for every entry with the same value in column?

OK, I'm a little outta practice on SQL Queries here, I have a table with thousands of entries. 好的,我这里有点SQL查询的练习,我有一个包含成千上万个条目的表。 Each row has a unique Id but there is a column named EquipmentId which is not unique and would be present in several rows. 每行都有一个唯一的ID,但是有一列名为EquipmentId的列不是唯一的,并且会出现在多行中。 I want to return 3 rows for every EquipmentId and if there is less the than 3 entries for an EquipmentID I want those too. 我想为每个EquipmentId返回3行,如果EquipmentID少于3个条目,我也想要这些行。 ..... make sense ? ..... 说得通 ? thanks in advance. 提前致谢。

Use ROW_NUMBER() + CTE 使用ROW_NUMBER() + CTE

;WITH CTE AS(
     SELECT *,
            ROW_NUMBER() OVER ( PARTITION BY EquipmentId  ORDER BY ID ) RN
     FROM TableName
)
SELECT * 
FROM CTE
WHERE RN <= 3 
ORDER BY EquipmentId    

Using subqueries you can do it like this: 使用子查询,您可以这样做:

SELECT * 
FROM
    (SELECT *, Rank() 
     OVER 
         (PARTITION BY equipmentid
          ORDER BY ID) Rank
     FROM stack) AS a 
WHERE
    rn <= 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM