2017-05-08 41 views
0

表1自定義SQL SELECT

ID  |  NAME  | INDICATOR | 
    ----------------------------------- 
    0001   Item1  Y 
    ----------------------------------- 
    0001   Item2  N 
    ----------------------------------- 
    0006   Item3  N 
    ----------------------------------- 
    0004   Item4  N 
    ----------------------------------- 
    0004   Item5  N  

表2

ID   INDICATOR 
    -------------------- 
    0001   Y 
    --------------------- 
    0002   Y 
    --------------------- 
    0003   Y 
    --------------------- 
    0004   Y 
    --------------------- 
    0005   N  

首先我需要選擇其指示爲Y在表2中,然後用該選擇我有選擇的名稱和IDS ID其指示器是N在表2中,

標準:

如果表2的ID是不presen t在table1中,那麼我的選擇應該爲NOTDEFINED返回一個名稱的值,而對於在table1中沒有Y的Id。

輸出結果進行

ID  |  NAME  
    ----------------------- 
    0001   Item1  
    ------------------------ 
    0002  NOTDEFINED 
    ------------------------ 
    0003  NOTDEFINED 
    ------------------------ 
    0004  NOTDEFINED 

是否有可能寫出這樣的選擇查詢,如果是好心幫。

+1

我刪除了不兼容的數據庫標記。請僅使用您正在使用的數據庫進行標記。 –

回答

0

你需要將取決於後端使用的是不同的SQL。例如用MS SQL服務器:

select a.id, 
    case when Indicator = 'N' then 'NOTDEFINED' else a.name end as Name 
from tableA a 
where exists (select * from tableB b where a.ID = b.ID and b.Indicator = 'Y'); 
0

嘗試以下查詢:

SELECT t2.ID ID, IF(t1.name <> NULL, t1.name, 'NOTDEFINED') NAME FROM Table2 t2 LEFT JOIN Table1 t1 ON (t2.ID = t1.id AND t1.INDICATOR = 'Y') GROUP BY t2.ID 
0

如果你的意思是說,你想它的指標是的Y表1然後用例1中的名字,否則,例如2應該回到你的要求。

--Example 1  
select table2.ID, isnull(table1.Name,'NOTDEFINED') from table2 
inner join table1 on table2.ID = table1.ID 
where table2.Indicator = 'Y' and table1.Indicator = 'N' 

--Example 2 
select table2.ID, isnull(table1.Name,'NOTDEFINED') from table2 
inner join table1 on table2.ID = table1.ID 
where table2.Indicator = 'Y' and table1.Indicator = 'Y'