比较SQL Server中同一列的数据

比较SQL Server中同一列的数据,sql,sql-server,Sql,Sql Server,我有一个表,其中有一列数据,如下所示: aaaa;1 aaaa;2 aaaa;3 bbbb;1 cccc;1 dddd;1 dddd;2 我需要选择分号(;)后面数字最大的数据,如下所示: aaaa;3 bbbb;1 cccc;1 dddd;2 有人能告诉我怎么做吗?使用CharIndex查找分号的位置,然后使用结果进行排序。示例代码如下: declare @table table ( col1 varchar(25) ) insert into @table (col1) values

我有一个表,其中有一列数据,如下所示:

aaaa;1
aaaa;2
aaaa;3
bbbb;1
cccc;1
dddd;1
dddd;2
我需要选择分号(
)后面数字最大的数据,如下所示:

aaaa;3
bbbb;1
cccc;1
dddd;2

有人能告诉我怎么做吗?

使用CharIndex查找分号的位置,然后使用结果进行排序。示例代码如下:

declare @table table (
col1 varchar(25)
)

insert into @table (col1) values ('aaaa;1')
insert into @table (col1) values ('aaaa;2')
insert into @table (col1) values ('aaaa;3')
insert into @table (col1) values ('bbbb;1')
insert into @table (col1) values ('dddd;1')
insert into @table (col1) values ('dddd;2')

select top 1
col1,
charindex(';',col1,0) as SemiColonLocation,
substring(col1, 0, charindex(';',col1,0) + 1) as TextVal,
substring(col1, charindex(';',col1,0) + 1, (len(col1) - charindex(';',col1,0))) as AfterVal
from @table
order by substring(col1, charindex(';',col1,0) + 1, (len(col1) - charindex(';',col1,0))) desc

您可以使用
LEFT
SUBSTRING
CHARINDEX
函数来实现这一点。更多信息请阅读本文

就这么简单:

select 
    -- Construct the string by left part + max(right part)
    LEFT([column], CHARINDEX(';', [column], 0) - 1) + ';' + 
    MAX(RIGHT([column], LEN([column]) - CHARINDEX(';', [column], 0)))
from 
    [table]
group by 
    LEFT([column], CHARINDEX(';', [column], 0) - 1) -- The left part of ';'
可以这样使用rank()


    select column_name
      from (select a.*,
                   rank() over(partition by substr(column_name, 1, 4) order by substr(column, 6) desc) as row_num
              from table_name a)
     where row_num = '1';

    select column_name
      from (select a.*,
                   rank() over(partition by substr(column_name, 1, 4) order by substr(column, 6) desc) as row_num
              from table_name a)
     where row_num = '1';