通过基于其他max table列连接表来从两个表中获取多个列

时间:2014-07-24 10:47:57

标签: sql sql-server

1)供应商表

--------------------------------------------
   VENDid    VENDname 
   ---      ----- 
    1        ABC
    2        XYZ
    3        WXY

2)购买表

---------------------------------------------  
VENDid   Purchasedate
------   ------------
1         12-01-2012
1         10-11-2013
2         22-02-2014
2         11-04-2014
3         10-05-2014
3         11-06-2014
1         14-06-2014     

输出(列出供应商表的所有行,仅列出购买表中的max(purchaseate))

---------------------------------------------
VENDid     VENDname     PurchaseDate
-------    --------     -------------
1          ABC          14-06-2014 
2          XYZ          11-04-2014    
3          WXY          11-06-2014  

我得到了一些问题,比如解决以前的问题 -

SELECT v.VendID, VendName, Max(PurchaseDate)
FROM vendor v
INNER JOIN purchase p
ON v.VendID = p.VendID
Group By v.VendID, VendName


select VENDid, VENDname, 
 (select top 1 purchaseDate from purchase p 
  where p.VENDid=v.VENDid order by purchaseDate desc) as 'Purchase date' 
from Vendor v

阙。如果我将在购买表中添加更多列,如 -

2)购买表

------------------------------------------    
    VENDid   Purchasedate   amount_paid
    ------   ------------   ------------
    1         12-01-2012    10000
    1         10-11-2013    20000
    2         22-02-2014    15000 
    2         11-04-2014    30000 
    3         10-05-2014    80000
    3         11-06-2014    17000
    1         14-06-2014    28000 

我希望amount_paid和之前的输出一样 -

---------------------------------------------
VENDid     VENDname     PurchaseDate     amount_paid
-------    --------     -------------    -------------
1          ABC          14-06-2014        28000
2          XYZ          11-04-2014        30000
3          WXY          11-06-2014        17000

那将是什么询问..

1 个答案:

答案 0 :(得分:1)

您似乎正在使用SQL Server。如果是这样,您可以使用cross apply

select v.VENDid, v.VENDname, p.PurchaseDate, p.Amount_Paid
from Vendor v cross apply
     (select top 1 p.*
      from purchase p 
      where p.VENDid = v.VENDid
      order by p.purchaseDate desc
     ) p ;