2017-11-30 15 views
0

내 데이터베이스에서이 쿼리를 실행하고 싶습니다. 두 테이블 A와 B가 하나의 많은 관계를 갖고 있지만 B.S에있는 최신 레코드가 필요합니다. 여기 내 쿼리는하위 쿼리가 EXISTS와 함께 도입되지 않은 경우 선택 목록에서 하나의 식만 지정할 수 있습니다. in subquery sqlserver

select *,(select top 1 ResultTest ,ResultState2 from B where GasReceptionId=A.Id order by Id desc) 
from A where OrganizationGasId= 4212 
입니다.

는하지만 난 당신이 각 레코드에서 오는에 포함 할 B에서 올바른 행의 데이터를 식별하는 분석 함수 (예를 들어, 행 번호)를 사용하는 조인 기본으로이 쿼리를 바꿔 수

Msg 116, Level 16, State 1, Line 2 
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS. 

답변

1

이 오류를 얻을 A 테이블.

SELECT * 
FROM 
(
    SELECT a.*, b.ResultTest, b.ResultState2, 
     ROW_NUMBER() OVER (PARTITION BY a.Id ORDER BY a.ID DESC) rn 
    FROM A a 
    LEFT JOIN B b 
     ON a.Id = b.GasReceptionId 
    WHERE 
     a.OrganizationGasId = 4212 
) t 
WHERE t.rn = 1; 
1

SELECT 절에 서브 쿼리는 정확히 하나의 열 (하나 또는 제로 행)를 반환해야합니다. ,

select 
    a.*, 
    (select top 1 resulttest from b where gasreceptionid = a.id order by id desc) as test, 
    (select top 1 resultstate2 from b where gasreceptionid = a.id order by id desc) as state 
from a 
where a.organizationgasid = 4212; 

또는 훨씬 더 FROM 절에 서브 쿼리를 이동 : 그래서 당신은 두 개의 하위 쿼리를 할 수 있습니다. 한 가지 방법은 OUTER APPLY입니다.

select 
    a.*, r.resulttest, r.resultstate2 
from a 
outer apply 
(
    select top 1 resulttest, resultstate2 
    from b 
    where gasreceptionid = a.id 
    order by id desc 
) r 
where a.organizationgasid = 4212;