SQL:如何加入2个SELECT语句

时间:2017-02-17 21:10:19

标签: sql sql-server select join

我正在尝试在SQL Server中加入这两个select语句,但是我收到了一个错误。

SELECT 
    t1.AutoNumber, t1.last_autonumber, t1.ContactID, t2.KeyValue_String
FROM
    (SELECT 
         la.autonumber, 
         LAG(la.autonumber, 1) OVER (PARTITION BY la.ContactID ORDER BY la.issuedate asc) AS last_autonumber,
         la.ContactID 
     FROM 
         loanagreements la
     ORDER BY 
         la.ContactID desc, la.issuedate asc) as t1
LEFT JOIN
    (SELECT 
         la.autonumber, es.KeyValue_String 
     FROM 
         loanagreements la
     JOIN 
         Enum.LoanStatuses es ON la.LoanStatus = es.KeyValue_Int) as t2 ON t1.last_autonumber = t2.autonumber

错误讯息:

  

Msg 1033,Level 15,State 1,Line 62
  除非还指定了TOP,OFFSET或FOR XML,否则ORDER BY子句在视图,内联函数,派生表,子查询和公用表表达式中无效。

     

Msg 102,Level 15,State 1,Line 65
  't2'附近的语法不正确。

1 个答案:

答案 0 :(得分:3)

你不能在子查询中使用order by。您可以编辑查询。试试这个。

select 
    t1.AutoNumber
  , t1.last_autonumber
  , t1.ContactID
  , t2.KeyValue_String
from (
    select 
        la.autonumber
      , last_autonumber = lag(la.autonumber, 1) over (
        partition by la.ContactID 
            order by la.issuedate asc
        )
    , la.ContactID
   from loanagreements la
   --order by la.ContactID desc, la.issuedate asc
   ) as t1
  left join (
   select 
      la.autonumber
    , es.KeyValue_String
    from loanagreements la
    inner join Enum.LoanStatuses es 
      on la.LoanStatus = es.KeyValue_Int
   ) as t2 
    on t1.last_autonumber = t2.autonumber