SQL查询以选择每个用户的最新5条记录?

时间:2019-07-03 09:02:32

标签: sql sql-server greatest-n-per-group

我有2个表“ Registration”和“ Enquery”。 注册:

Id  User_id     name      Phone          Address
1   biz_1445    Ajinkya   5555555555    Delhi
2   biz_1256    Shubham   45698745      Mumbai
3   biz_2658    shikhar   523698        Nagpur

查询:

Enq_Id  enq_name         enq_details            user_id
1       skycam           call for visit         biz_1445
2       websort          visit                  biz_2658
3       reliance         order of 100items      biz_1445    
4       Digital-Shoppe   enquire about 6 PC.    biz_1445

基本工作是:销售人员通过他的应用程序输入数据,并将其提交到查询表中。现在,我想显示各个销售人员的最新5个条目,并在我的应用程序中的recyclerview中显示它。 SQl逻辑吗?

3 个答案:

答案 0 :(得分:1)

首先,您需要了解{strong>询问提交人的user_id。 假设此ID为current_user_id

因此查询应类似于-

select * 
from (
    select top 5 Enq_Id, enq_name, enq_details 
    from Enquery where user_id = current_user_id 
    order by Enq_Id desc
) a 
order by Enq_Id asc

答案 1 :(得分:0)

以下查询应执行您想要的操作:

SELECT * 
FROM (
SELECT reg.name,reg.Phone,reg.Address,enq.[user_id],enq.[Enq_Id]
    ,enq.enq_name
    ,enq.enq_details
    ,ROW_NUMBER() OVER(PARTITION BY enq.[user_id] ORDER BY enq.[Enq_Id] DESC) AS RNO
FROM [Enquery] enq
INNER JOIN [Registration] reg ON enq.[User_id] = reg.[User_id] ) A
WHERE RNO <= 5

答案 2 :(得分:-3)

用于显示销售人员5条最新记录的SQL查询:

return DB:table('Registration')->join('Enquery', 'Registration.User_id', 'Enquery.user_id')
 ->OrderBy('Enq_id', 'desc')
 ->where('Enquery.user_id', '=', 'Registration.User_id')
 ->distinct()