首页 > 解决方案 > 如何比较具有相同开头和不同结尾的 SQL 条目?

问题描述

基本上,我要比较的行的格式有点像这样:[Form Code]_[Version Date (mm/yy)]。

更新表单时,它们使用相同的代码,但更改版本日期以反映它何时生效。因此,您可能会看到 Example_Code_12_01,然后将其替换为 Example_Code_12_17。

我要做的是编写一个 SQL Server 查询,该查询将遍历这些表单中的每一个,所有表单都具有不同的表单代码,并返回两个具有相同代码但版本日期不同的表单。

我在想它会是这样的:

select a.FullFormName, b.FullFormName
from Forms a
join Forms b on --here is where the logic for the compare would go--
where a.FullFormName != b.FullFormName
--The above is to make sure it doesn't return the same exact form twice

标签: sqlsql-server

解决方案


您似乎想要在没有最后 6 个字符的情况下进行比较:

select a.FullFormName, b.FullFormName
from Forms a join
     Forms b
     on left(a.FullFormName, len(a.FullFormName) - 6) = left(b.FullFormName, len(b.FullFormName) - 6)  --here is where the logic for the compare would go--
where a.FullFormName <> b.FullFormName;

推荐阅读