2015-09-04 159 views
0

回顧一些代碼,我絆倒這個SQL代碼,我不明白它在做什麼。解釋代碼

INNER JOIN PPORDFIL_SQL 
    on dbo.att_Synergy_Absences.ItemCode = PPORDFIL_SQL.item_no 
    and PPORDFIL_SQL.id in 
     (Select top 1 p2.ID 
     from PPORDFIL_SQL as p2 
     where p2.item_no = PPORDFIL_SQL.item_no 
      and p2.ord_status = PPORDFIL_SQL.ord_status 
      and dbo.att_Synergy_Absences.syscreated <= ppordfil_sql.entered_dt 
     order by p2.id) 

據我的理解,假設無論最早的條目是什麼,都會顯示1條記錄。

例如,同一個item_no有多個項目,但是訂單號碼不同,所以即使存在多個相同item_no的訂單號,它也只會顯示一個項目。

我試圖運行代碼,但它沒有奏效。

對它做了什麼或做了什麼評論我實際上是否正確?大聲笑

+1

這是一個偉大的地方開始得到答案。 http://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/ –

+0

你的子查詢按ID排序 - 也許應該按日期排序而不是? –

回答

0

你的兩個連接條件互相干擾。

試試這樣說:

INNER JOIN PPORDFIL_SQL on PPORDFIL_SQL.id = (
    Select top 1 p2.ID 
    from PPORDFIL_SQL as p2 
    where p2.item_no = dbo.att_Synergy_Absences.ItemCode 
    and p2.ord_status = PPORDFIL_SQL.ord_status 
    and dbo.att_Synergy_Absences.syscreated <= ppordfil_sql.entered_dt 
    order by p2.id 
)