我只需要列出我数据库中公司的前五个请求。我有两个名为Request and Company的表。对给定公司可能有任何数量的请求。但是,我需要查询并仅列出我数据库中所有公司的前5个请求。
select top 5 *
from Request as r
INNER JOIN Company c
ON r.Company_id=c.Company_ID
我已完成上述查询,但它只返回表中的前五个而不是所有成员的前五个。如何更正我的查询?
答案 0 :(得分: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
答案 1 :(得分: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
的位置:
{{1}}
答案 2 :(得分:0)
您需要按确定'第一性'的字段进行排序。可能类似于:
ORDER BY r.RequestDate
答案 3 :(得分: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