![](/img/trans.png)
[英]Temporary table with two tables data with no column in common should return data in one column
[英]How to compare two tables with one table having a temporary column name
我有兩個表,都帶有ID_Number和version列。 但是,ID_number的格式不同。 我的目標是比較兩個表並輸出具有相同ID_number但版本不同的任何行。
格式差異如下:
例如。 第一個表中的ID號為“ 23-4567”。 第二個表中的對應ID號為“ 1023004567”。 在“ 23”之前添加“ 10”,並用“ 00”替換“-”。 所有ID均相同。
首先,我使用“子字符串”使table1中的ID_Number與table2中的ID_Number匹配,並將此新列重命名為newIDNumber(table1),然后將newIDNumber(table1)與ID_Number(table2)進行比較。 上面示例中要在表1中轉換ID_Number的代碼是這樣的,
Eg. '10' + SUBSTRING(@ID_number, 1, 2) + '00' + SUBSTRING(@ID_number, 4,4) AS newIDNumber
現在,我編寫以下代碼來檢查版本差異
SELECT ID_Number, version, "10" + SUBSTRING(@ID_number, 1, 2) + "00" + SUBSTRING(@ID_number, 4,4) (From first table) AS newIDNumber
FROM table1
WHERE (NOT EXISTS
(SELECT ID_Number, version
FROM table2
WHERE (table1.newIDNumber= table2.ID_Number) AND (table1.version = table2.version)
)
)
它輸出一個錯誤,指出“'where子句'中的未知列'table1.newIDNumber'”。 如何在不中斷數據庫的情況下進行比較(將newIDNumber列插入到table1中)?
“ declare newIDNumber”是否有效?
SELECT
ID_Number
, version
FROM
table1
WHERE
NOT EXISTS
(
SELECT 1
FROM table2
WHERE
"10" + SUBSTRING(table1.ID_number, 1, 2)
+ "00" + SUBSTRING(table1.ID_number, 4,4) = table2.ID_Number
AND table1.version = table2.version
)
您應該拋出一些樣本數據。
嘗試這個,
declare @t table(col1 varchar(50))
insert into @t values('23-4567')
declare @t1 table(col1 varchar(50))
insert into @t1 values('1023004567')
;With CTE as
(
select t.col1
from @t t
inner join @t1 t1
on substring(t.col1,1,charindex('-',t.col1)-1)=
substring(t1.col1,charindex('10',t1.col1)+2,charindex('00',t1.col1)-3)
where NOT EXISTS(
select * from @t1 t1
where substring(t.col1,charindex('-',t.col1)+1,len(col1))
=substring(t1.col1,charindex('00',t1.col1)+2,len(col1))
)
)
select * from cte t
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.