簡體   English   中英

自聯接SQL Server 2008中的表

[英]Self-join a table in SQL Server 2008

我想在一張桌子上使用INNER JOIN 但我收到此錯誤消息:

消息208,第16級,狀態1,第1行
無效的對象名稱“ a”。

我的查詢是:

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  

更新

在此處輸入圖片說明

用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  

也許是這樣嗎?

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 

我覺得這里a是一個別名,而不是表名。 因此,SQL SERVER不允許a再創建一個別名b

因此,如果您想使用與a相同的表,則還必須重寫b子查詢。

喜歡,

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  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM