[英]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.