0

我只需要从我的数据库中列出对公司的前五个请求。我有两个名为 Request 和 Company 的表。对于给定的公司,可能有任何数量的请求。但是,我只需要查询并列出数据库中所有公司的前 5 个请求。

select top 5 *
from Request as r 
    INNER JOIN Company c
    ON r.Company_id=c.Company_ID

我已经完成了上述查询,但它只返回表中的前五个而不是所有成员的前五个。如何更正我的查询?

4

4 回答 4

2
    With r 
    as
    (select  *, row_number() over(partition by Company_id order by RequestDate) as rown
    from Request as)
    Select *
from r join Company c on c.Company_id=r.Company_id
    Where rown<=5
于 2012-05-17T14:29:17.003 回答
1

认为您正在为您的公司表中存在的每家公司寻找前 5 个请求。在这种情况下,您可以rank()在子选择中按公司提出每个请求,然后选择排名在哪里<= 5

select company_id, request_id
from
    ( select c.company_id, r.request_id, rank() over (partition by c.company_id order by request_id) as Rank
    from request r
    inner join company c on
        r.company_id = c.company_id
    ) ranked
where rank <= 5
于 2012-05-17T14:32:19.597 回答
0

您需要按确定“第一”的字段排序。大概是这样的:

ORDER BY r.RequestDate

于 2012-05-17T14:30:56.697 回答
0
;WITH companyrecords 
     AS (SELECT Company.*, 
                Row_number() OVER (partition BY r.Company_id ORDER BY 
                r.Company_id 
                ASC) 
                   AS 
                RowNumber 
         FROM   Request AS r 
                INNER JOIN Company c 
                  ON r.Company_id = c.Company_ID) 
SELECT * 
FROM   companyrecords 
WHERE  RowNumber <= 5 
于 2012-05-17T14:31:24.913 回答