每记录乘数一个记录

时间:2013-11-22 20:11:14

标签: sql sql-server tsql

[Links]
LinkID, Link  
1,http:/link1  
2,http:/link2  

[Link2Page]  
LinkID, PageID

1,1  
1,2  
1,3  
2,3   
2,4  
2,5  

[Pages] PageID, Title, Url , EndPage(bit)

1, title page 1 , http:/page1 , false  
2, title page 2 , http:/page2 , true  
3, title page 3 , http:/page3 , false  
4, title page 4 , http:/page4 , false  
5, title page 5 , http:/page5 , true  

我想从endPage desc

列出页面顺序列出所有链接和1条记录

例如

LinkId , Link , PageID , Title , Url  
1 , http:/link1 , 2 , title page 2 , http:/page2  
2 , http:/link2 , 5 , title page 5 , http:/page5  
...

LinkiPage中存在的每个记录的Page i选择就像

( Select TOP 1 PageID,Title,Url from Pages Order By EndPage Desc )

我得到的更接近的是:

Select LinkID , Link , ( Select TOP 1 PageID From Pages Where PageID IN ( Select PageID From Link2Page Where Link2Page.LinkID = Links.LinkID ) ) as PageID From Links;

但我错过了其他专栏(Pages.Title,Pages.Url)等

Lame尝试(?):

  

选择LinkID,Link,

     

(从PageID IN的页面中选择TOP 1 PageID(从Link2Page中选择PageID,其中Link2Page.LinkID = Links.LinkID))作为PageID,

     

(从PageID IN页面中选择TOP 1 URL(从Link2Page中选择PageID,其中Link2Page.LinkID = Links.LinkID))作为URL,

     

(从PageID IN的页面中选择TOP 1 Title(从Link2Page中选择PageID,其中Link2Page.LinkID = Links.LinkID))作为标题

     

来自链接;`

1 个答案:

答案 0 :(得分:0)

SELECT *
FROM Links l
CROSS APPLY (
  SELECT TOP 1 p.*
  FROM Pages p
  INNER JOIN Link2Page x ON (x.PageID = p.PageID)
  WHERE x.LinkID = l.LinkID
  ORDER BY EndPage DESC
) p