2013-05-30 70 views
1

檢索多個表的數據,我有5個表如何使用是/否縮寫

Village 

enter image description here


T1_Master (Village_ID is a foreign key) 

enter image description here


T2_Master (Village_ID is a foreign key) 

enter image description here


T1_Details (t1_id is a foreign key) & (month,year,t1_id are combination of primary key(複合鍵))

enter image description here


T2_Details (t2_id is a foreign key) & (month,year,t2_id are combination of primary key(複合鍵)) enter image description here

現在,如果我要重新trieve的記錄,其中village_ID = 01, month=03 and year=2013

然後輸出應該像下面

enter image description here

here t1_1(No) = t1_1 has no record for month=03 and year=2013 

Like wise t2_1(Yes) = t2_1 has record for month=03 and year=2013等等...

plz幫助我.... PLZ

+0

請出示您嘗試編寫查詢。 –

回答

0

我想你想要一個或多個左或右連接:

SELECT 
    V.Village_ID  
    , Dates.[MONTH] 
    , Dates.[YEAR] 
    , CASE WHEN colValue IS NULL THEN 'no' 
     ELSE 'yes' 
     END [Yes or No] 
FROM 
    (
    SELECT 
     Village_ID 
    FROM 
     Villages 
    WHERE 
     Village_ID = @ParamVilageID 
    ) V 
    LEFT JOIN 
    (
    SELECT 
     Viilage_ID 
     , [MONTH] 
     , [YEAR] 
    FROM 
     T1_Details 
    WHERE 
     [MONTH] = @ParamMonth 
     AND 
     [YEAR] = @ParamYear 
    ) Dates 
    ON V.Village_ID = Dates.Village_ID 

您需要決定將哪個列引用爲colValue,但所有SQL元素都在那裏。 SQL將推斷數據類型(字符串)從案件陳述,但你可以返回直布爾0或1

順便說一句,有一個單一的smallDate列會更好,因爲SQL有DatePart和DateName函數

0

您將需要使用外連接來獲取空值(您可能需要考慮在左連接上找到一些可用的教程 - 在Google上有很多)。關鍵是在細節行不可用時使用主表來顯示id。

SELECT v.Village_id, 
     CASE WHEN t1d.t1_id IS NULL THEN CAST(t1m.t1_id AS VARCHAR(50)) + ' (No)' 
       ELSE CAST(t1m.t1_id AS VARCHAR(50)) + ' (Yes)' 
     END T1, 
     CASE WHEN t2d.t2_id IS NULL THEN CAST(t2m.t2_id AS VARCHAR(50)) + ' (No)' 
       ELSE CAST(t2m.t2_id AS VARCHAR(50)) + ' (Yes)' 
     END T2 
FROM Village v 
     LEFT OUTER JOIN T1_Master t1m 
     ON t1m.Village_ID = v.Village_ID 
     LEFT OUTER JOIN T1_Details t1d 
     ON t1d.t1_id = t1m.t1_id 
      AND t1d.[month] = 03 
      AND t1d.[year] = 2013 
     LEFT OUTER JOIN T2_Master t2m 
     ON t2m.Village_ID = v.Village_ID 
     LEFT OUTER JOIN T2_Details t2d 
     ON t2d.t2_id = t2m.t2_id 
      AND t2d.[month] = 03 
      AND t2d.[year] = 2013 
WHERE v.Village_ID = 01 

根據您的空值的數據庫設置,CAST(t2m.t2_id AS VARCHAR(50)) + ' (No)'語句可能需要進行檢查,看是否T2M記錄爲空讓它顯示空而不只是「(無)」