在SQL中获取值和类似的值

时间:2014-06-27 20:12:45

标签: sql sql-server-2008

我有一个包含以下

的SQL表
ID     AccountNumber     Name
1      12345             Tony
2      123456            Mike
3      123458            Mike
4      45689             Tom
5      666999            Tim
6      6669997           Lisa
7      44455             Tim
8      78901             Matt
9      789011            Roger

我需要做的是向我展示帐号以相同值(不确定数字)开头的所有记录。例如。在此表中,我想选择并显示以下内容:

12345
123456
123458

666999
6669997

78901
789011

如您所见,它显示了AccountNumber匹配的每一行或具有相同的起始编号。我无法找到正确的查询,并希望得到任何帮助。

谢谢!

3 个答案:

答案 0 :(得分:1)

你提到的案例满足时间越长,越短。这是一个查询,它将获得每个帐号的最短匹配:

select AccountNumber
from (select a.*, count(*) over (partition by ShortestAN) as numAN
      from (select a.*,
                   (select top 1 a2.AccountNumber
                    from accounts a2
                    where a.AccountNumber like a2.AccountNumber + '%'
                    order by length(a2.AccountNumber) asc
                   ) as ShortestAN
            from accounts a
           ) a
     ) a
where numAN > 1
order by ShortestAN, AccountNumber;

子查询找到匹配的最短帐号。其余的只是返回有多个匹配的那些。

答案 1 :(得分:0)

select a1.ID, a1.AccountNumber, a1.Name, 
a2.ID, a2.AccountNumber, a2.Name
from Accounts a1 
join Accounts a2 on LEN(a1.name) <= LEN(a2.name) and SUBSTRING(a2.name, 1, LEN(a1.name)) = a1.name
where /*are not same rows*/ a1.ID <> a2.ID

答案 2 :(得分:0)

如果按顺序排序,是不是按工作顺序?

SELECT AccountNumber, Id, Name
FROM Accounts
ORDER BY CAST(AccountNumber AS NVARCHAR(50))