SQL比较两列,数据略有不同

时间:2017-08-15 21:00:56

标签: sql

我在不同的服务器上有两个表,我需要链接他们共有的列。但是,列中的数据会略有不同。

我有两张桌子,一张是临时桌子,我有他们需要的学生名单,他们的全名,dob,地址和他们参加的课后计划,以及计划ID,每个程序都有一个id。另一个表包含所有程序信息及其ID和位置,这些信息当前存在于我们的系统中。

另一个表包含所有ID,但这个数据长度为5个字符,并非所有数据都以“0”结尾。现在我需要加入这个在我的第一张桌子上有5个字符长数据的表,并说这个ID在我桌子上的所有学生都属于这个ID。

#students

StudentID  Lastname      Firstname       dob         Afterschool_program     location         Department     programID 
--------------------------------------------------------------------------------------------
81EB       Toreros     Christian         03/26/1999  Teen Dance Exercise     158-Bayshore    Theater            5269  
89EB       Willis      Michael           03/15/2002  Arts Painting  158-Mulan Drive    Arts          6985  

其他表格地点

 locationName                                                          Address                            LocationID
 ---------------------------------------------------------------------------------------------------------------------          
    Bay Shore - DAY Program / Scie- TEEN & YOUNG ADULTS - 52690           BayShore 123-89 place                  52690   
Mulan - DAY Program / Arts- TEEN - 96850           BayShore 123-89 place                  52690 

问题是如何将locationID加入programID

到目前为止,我已尝试过这个

IF OBJECT_ID('tempdb..#locationsID') IS NOT NULL 
     DROP TABLE #locationsID

SELECT DISTINCT
    LEFT(RTRIM(LocationID), 4) AS Location_ID, LocationName 
INTO
    #locationsID
FROM
    locationstable
ORDER BY
    LocationID 

--select * from #locationsID 

IF OBJECT_ID('tempdb..#locomparison') IS NOT NULL 
    DROP TABLE #locomparison 

SELECT DISTINCT 
    cloc.LocationID, pfm.programID as programID 
INTO
    #locomparison
FROM
    #locationsID  cloc
LEFT OUTER JOIN 
    tablewithlivesystemdata pfm ON pfm.programID = cloc.Location_ID
ORDER BY
    LocationID

--Main
SELECT
    programID, LocationID, * 
FROM
    Students
JOIN
    #locomparison ON LocationID.#locomparison = programID.#Students

但这不起作用:(

3 个答案:

答案 0 :(得分:0)

您可以匹配部分字符串。如果locationID长度为5个字符,则以下左侧函数返回最左边的4个字符。

select s.programID, l.LocationID
from #students s
join #Locations l on s.programID = LEFT(LocationID, LEN(LocationID)-1);

答案 1 :(得分:0)

如果programID和locationID都是INTeger类型,则使用CAST()

SELECT *
  FROM #students s
  LEFT OUTER JOIN #Locations l 
    ON s.programID = CAST(LEFT(CAST(locationID AS VARCHAR(50)),4) AS INT);

答案 2 :(得分:0)

假设这些列是VARCHAR,您可以使用LIKE条件:

select s.programID, l.LocationID
from #students s
join #Locations l on l.LocationID LIKE s.programID + '%';

如果它们是INT,您应该首先将它们转换为VARCHAR:

select s.programID, l.LocationID
from #students s
join #Locations l on convert(varchar(50), l.LocationID) LIKE convert(varchar(50), s.programID) + '%';

或者,如果LocationID总是比ProgramID大10倍,您可以使用:

select s.programID, l.LocationID
from #students s
join #Locations l on l.LocationID = s.programID * 10;