2012-10-28 2 views
1

다음은 내가 원하는 의사 코드입니다. 다음 문장에서 주먹 동맹의 수를 얻어야합니다.여러 테이블로 통합 된 첫 번째 테이블 수 얻기

SELECT * 
FROM Table1 
UNION 
SELECT Cats.Id + (SELECT COUNT(*) FROM Fist_Union_Result), 
     Cats.Name 
FROM Table2 

어떤 생각? 이 같은

+0

의 중복 가능성 http://stackoverflow.com/questions/13108810/ado-net -entitydatasource-error-the-right-expression-must-be-of-of-number-or-str) –

+0

첫 번째 select 문에서만 또는 둘 모두에서 COUNT (*)를? –

+0

예제 데이터 및 예상 결과 설명 – Laurence

답변

1

첫 번째 부분이 복잡한 쿼리라고 가정하면 with 절을 사용하여 별칭을 지정할 수 있습니다. 즉, 당신이 두 장소에서 사용할 수 있으며, 노조의 상단 부분과 장소는 당신이 계산 여기서 그냥 고유 ID를 원하는 경우

; with FirstPart as 
     (
     select * 
     from Table1 
     ) 
select * 
from FirstPart 
union all 
select cats.Id - cnt.cnt 
,  cats.Name 
from Table2 cats 
cross join 
     (
     select count(*) as cnt 
     from FistPart 
     ) as cnt 

, 당신은 하위 쿼리에 union를 배치하고 단지 레이블 수 로우 1..N :

select row_number() over (order by Name) as Id 
,  Name 
from (
     select Name 
     from Table1 
     union all 
     select Name 
     from Table2 
     ) as SubQueryAlias 
[오른쪽 숫자 식 또는 문자열 유형이어야 ADO.NET EntityDataSource 오류 >> (
+0

감사합니다. with 절이 내 문제를 해결했다. –

0

뭔가 :

with first_union_result as (
    select col1, 
     col2 
    from table1 
), count_from_first as (
    select count(*) as first_count 
    from first_union_result 
) 
select col1, 
     col2 
from first_union_result 
union all 
select cats.id + cnt.first_count, 
     cats.name 
from cats 
    cross join count_from_first as cnt; 

일부 고유 ID 또는 전체 결과에 비슷한려고하는 경우 모든 행이를 생성하는 row_number()를 사용하여 더 나을 수 있습니다.

+0

답변 해 주셔서 감사합니다. Andomar의 대답이 내 문제를 해결했습니다. –

관련 문제