我的表格中有一个包含以下数据的列:
aaaa;1
aaaa;2
aaaa;3
bbbb;1
cccc;1
dddd;1
dddd;2
我需要在分号(;
)之后选择编号最大的数据,如下所示:
aaaa;3
bbbb;1
cccc;1
dddd;2
有人能告诉我如何做到这一点吗?
答案 0 :(得分:2)
这很简单:
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 ';'
答案 1 :(得分:0)
使用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
答案 2 :(得分:0)
您可以使用LEFT
,SUBSTRING
和CHARINDEX
功能来实现此目的。有关详细信息,请阅读此article。
WITH CteSplit(string, leftString, rightString, RN) AS(
SELECT
string,
LEFT(string, CHARINDEX(';', string, 0) - 1),
CAST(SUBSTRING(string, CHARINDEX(';', string, 0) + 1, LEN(string) - CHARINDEX(';', string, 0)) AS INT),
RN = ROW_NUMBER() OVER(
PARTITION BY
LEFT(string, CHARINDEX(';', string, 0) - 1)
ORDER BY
CAST(SUBSTRING(string, CHARINDEX(';', string, 0) + 1, LEN(string) - CHARINDEX(';', string, 0)) AS INT) DESC
)
FROM TestTable
)
SELECT
string
FROM CteSplit
WHERE RN = 1
答案 3 :(得分:0)
你可以像这样使用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';