简体   繁体   中英

Self-join a table in SQL Server 2008

I would like to use INNER JOIN on one table. But I get this error message:

Msg 208, Level 16, State 1, Line 1
Invalid object name 'a'.

My query is :

select * 
from 
    (select 
         *,
         ROW_NUMBER() OVER (ORDER BY GoodMainCode) as row 
     from [SarMem].[dbo].[Book_Data1]  
     where GoodName like '%A%' and GroupCode = 115) a 
  inner join a b on b.GoodMainCode = a.GoodMainCode 
where a.row > 0 and a.row <= 100  

updated

在此处输入图片说明

Do it with cte:

;with a as(select *, ROW_NUMBER() OVER (ORDER BY GoodMainCode) as row 
           from [SarMem].[dbo].[Book_Data1]  
           where GoodName like '%A%' and GroupCode = 115) 
 select * from a
 join a b on b.GoodMainCode = a.GoodMainCode
 where a.row > 0 and a.row <= 100  

Maybe something like that?

WITH List AS (
SELECT 
    ROW_NUMBER() OVER (ORDER BY GoodMainCode) AS Row, *  
FROM
    [SarMem].[dbo].[Book_Data1]
WHERE
    ( GoodName like '%A%' )
    AND ( GroupCode = 115 )
) 
SELECT *  FROM List WHERE Row between 1 and 100 

I think here a is an alias name not the table name. So SQL SERVER won't allow a to create one more alias b .

So if you wanna use same table as a , then you have to rewrite subquery for b also.

Like,

select * from (
select *,ROW_NUMBER() OVER (ORDER BY GoodMainCode) as row from [SarMem].[dbo].[Book_Data1]  where GoodName like '%A%'  and GroupCode = 115  ) a 
 INNER  JOIN (
select *,ROW_NUMBER() OVER (ORDER BY GoodMainCode) as row from [SarMem].[dbo].[Book_Data1]  where GoodName like '%A%'  and GroupCode = 115  ) b on b.GoodMainCode = a.GoodMainCode where  a.row > 0 and a.row <= 100  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM