2014-06-23 57 views
0

我有兩個表A和表BSQL JOIN表,部分中選擇數據條件

表A包含的ID,號碼,時間,值1

表B包含的ID,數據,值2

Example of the Record on Table A: 

Id  Number  Tried  Value1 
------- ---------- --------- --------- 
1  123  23   5 
2  124  23   6 
3  1254  23   7 

Example of the Record on Table B: 

Id  Data  Value2 
------ --------- ------- 
1  123,23  6 
2  122,21  5 
3  1254,23 7 

我的目的是通過表B的連接條件將值1和值2加在一起。數據與表A的數字並試圖匹配記錄。

Example : 
Id  (Value1 + Value2) 
------- ----------------- 
1  11 
3  14 

我的查詢:

select a.Id , a.Value1+ b.Value2 
from a 
join b on substring(b.Data,1,3) = a.Number and substring(b.Data,5,2) = a.Tried 

我曾試圖串,但數據記錄長度的值是不同的比較上ID爲1,3和查詢結果的當前只顯示編號1.是否有其他辦法加入1列分成兩種值的列分別取出','加入表2中的2個字段?

+1

使用這樣的連接字符串作爲外鍵是一個可怕的想法。你絕對需要加入嗎? – mareckmareck

回答

0

檢查此查詢會有所幫助,在甲骨文

select a.Id , (a.Value1+ b.Value2) 
from a, b 
where a.id = b.id and b.Data = (a.Number || ',' || a.Tried); 

編輯:基於@Joachim伊薩克森建議:

select a.Id ,b.Id (a.Value1+ b.Value2) 
from a, b 
where b.Data = (a.Number || ',' || a.Tried); 
+0

我不確定a.id = b.id應該是一個標準。 –

+0

@JoachimIsaksson:根據您的輸入修改答案。謝謝! –

0

您可以使用下面的查詢。

select A.Id, (A.Value1 + B.Value2) [Value1 + Value2] from tblA A 
    inner join tblB B on A.Number = SUBSTRING(B.Data, 1, charindex(',', B.Data, 1) - 1) 
     And A.Tried = SUBSTRING(B.Data, charindex(',', B.Data, 1) + 1, Len(A.Tried)) 

這我已經在SQL Server中嘗試過了。

Nishanthi Grashia的查詢也可以在SQL Server中進行轉換。你只需要更換||+