2012-06-29 49 views
0

First_table查詢爲連接兩個表可能出現的多個映射

srno wono Actual_Start_Date Actual_End_Date 
1  31  2012-06-02   2012-06-05 
2  32  2012-06-05   2012-06-22 
3  33  2012-06-11   2012-06-23 
4  34  2012-06-23   2012-06-30 
5  A-2 2012-06-24   2012-06-25 
6  BU  2012-06-24   2012-06-26 
7  40  2012-06-25   2012-06-27 

second_table

srno wono Base_start_date  Base_end_date uploadhistoryid 
1  31  2012-06-05   2012-06-05   1 
2  32  2012-06-11   2012-06-12   2 
3  32  2012-06-15   2012-06-17   3 
4  32  2012-06-18   2012-06-20   4 
5  33  2012-06-22   2012-06-25   5 
5  33  2012-06-23   2012-06-25   5 

結果所需

SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
ALTER PROCEDURE [dbo].[Reports_Subanalysis] 
(
@WONo VARCHAR(20) 
) 
AS 
BEGIN 

SELECT 
      'SAT' AS stage, 
        s.Base_start_date AS start_date, 
        s.Base_end_date AS end_date, 
        f.Actual_Start_Date AS Actual_Start_Date, 
        f.Actual_end_Date AS Actual_End_Date 
        FROM First_table f, 
        second_table B 
        WHERE A.wOno=B.nOno 
        AND f.uploadhistoryid in (SELECT min(uploadhistoryid) FROM second_table C WHERE f.wono = C.wono) 
        AND [email protected] 

END 
當我通過

'32'

結果

stage start_date  end_date  Actual_Start_Date Actual_End_Date 

SAT  2012-06-11  2012-06-12  2012-06-05   2012-06-05 

我怎樣才能得到這樣的結果,當我傳似不匹配值「卜」

stage start_date  end_date  Actual_Start_Date Actual_End_Date 
SAT  NULL   NULL   2012-06-24   2012-06-26 

我需要在我的日常什麼修改?

+0

啊,又一個 「如何做一個加盟」 的問題。這些必須佔SO上所有問題的10%。嘗試http://howtodoajoin.stackexchange.com。 – Ben

+0

@Ben:該鏈接無法打開。 (或者,更確切地說,它說,'找不到howtodoajoin.stackexchange.com') –

+0

@AndriyM,但它*應該*存在... – Ben

回答

0

您將需要使用左連接加入第二個表。還可以使用 - ˚F .wono = @ WONo

SELECT TOP 1    
'SAT' AS stage,      
    s.Base_start_date AS start_date,      
    s.Base_end_date AS end_date,      
    f.Actual_Start_Date AS Actual_Start_Date,      
    f.Actual_end_Date AS Actual_End_Date      
FROM First_table f      
LEFT JOIN second_table s ON f.wOno=s.nOno 
WHERE 
[email protected] 
ORDER BY s.uploadhistoryid ASC 
+0

這個左連接在這裏不工作..即使有在第二個表中沒有匹配的'BU',如何處理在第二個表 – syncdm2012

+0

ur查詢別名中沒有的b.uploadhistoryid是非常不清楚的,你需要修復。我已經刪除你的內部查詢部分,並取而代之的限制和順序。查看上面更新的查詢 – Kshitij

+0

@ Kshitij剛更新了查詢右側的別名,請檢查。如上所述,我需要傳遞'BU'時需要的結果。 – syncdm2012