-2

有 2 张桌子,我只想为之前订购的每个客户选择最后一个订单...

(cid,cname) 客户表

1、大卫

2、汤姆

3、亚历克斯

(oid,cid,title,ordertime) 订单表

1,1,"T恤",2013-10-1

2,3,《球》,2013-10-1

3,3,《食品》,2013-11-20

*根据汤姆从未订购过的表格。所以他不会被列出来。亚历克斯之前订购了 2 次,我只想显示最后一个订单。

输出必须是这样的:*

1,1,《T恤》,2013-10-1,大卫

3,3,《美食》,2013-11-20,亚历克斯

我尝试了类似此代码的方法,但 Alex 被列出了 2 次。我不明白我怎么能弄清楚。

select * 
from   Clients t2 
  left join Orders t1 
  on t1.cid=t2.cid 
where t1.ordertime<getutcdate() 
order by t1.ordertime desc**

可能我必须使用 Distinct 或 Group by,但我不明白如何。

4

3 回答 3

0
Select
    x.oid, 
    x.cid, 
    x.title, 
    x.ordertime,
    x.cname
From (
    Select
        o.oid, 
        o.cid, 
        o.title, 
        o.ordertime,
        c.cname,
        row_number() over (partition by o.cid order by o.ordertime desc) rn
    From
        Clients c
            inner join
        Orders o
            on c.cid = o.cid
    ) x
Where
    x.rn = 1
于 2013-11-09T00:40:00.757 回答
0
SELECT o.*, c.name
FROM orders o INNER JOIN clients c on o.cid = c.cid 
INNER JOIN (SELECT MAX(oid) as latestOrderid, cid FROM orders GROUP BY  cid) as latest
on latest.latestorderid= orders.oid
于 2013-11-09T00:40:18.407 回答
0

尝试这个:

select o.*, c.cname
from clients c
join orders o on 
    c.cid = o.cid 
    and not exists (select * 
                    from orders o2 
                    where o2.cid = o.cid 
                        and o2.ordertime > o.ordertime) 
于 2013-11-09T00:40:53.823 回答