我有2张桌子..一张客户桌......订单表......我试图从每个客户那里得到最后6个订单,但是对于所有的客户......我很难想到如何这样做哈哈..周五......任何帮助/想法? ..我正在使用microsoft sql server studio,如果你需要知道
这是我现在的代码
select /*top 6*/ c.Company_name, oh.qms_control_nbr, c.reminder_notice
from orderheader oh inner join clients c on oh.prnt_id = c.id
where c.status = 'Active'
group by c.company_name, oh.date_ordered, oh.qms_control_nbr, c.reminder_notice
order by c.company_name asc, c.reminder_notice asc, oh.Date_ordered desc
这给了我每个客户的所有订单,..只想限制到最后6个
所以......可能会给出这样的结果
_company_____ __order-num___
company a 1111
company a 1112
company a 1113
company a 1114
company a 1115
company a 1116
company b 1221
company b 1222
company b 1433
company b 1524
company b 1345
company b 1436
答案 0 :(得分:2)
您可以使用ROW_NUMBER
OLAP函数来获取此信息:
根据相关新信息进行修改。我认为这应该可以满足您的需求:
SELECT c.Company_name, oh.qms_control_nbr, c.reminder_notice
FROM (SELECT t.*,
ROW_NUMBER() OVER (PARTITION BY prnt_id ORDER BY date_ordered DESC) AS RN
FROM orderheader t) oh
JOIN clients c
ON oh.prnt_id = c.id
WHERE c.status = 'Active'
AND oh.rn < 7
ORDER BY c.company_name asc, c.reminder_notice asc, oh.Date_ordered desc
答案 1 :(得分:1)
select top 6 o.* from clienttable c
inner join orderstable o on c.columname = o.columnname
order by o.OrderProcessDate desc
将columnname
和OrderProcessDate
替换为正确的列。