【问题标题】:SQL: extract common string from by groupSQL:按组提取公共字符串
【发布时间】:2018-10-21 06:24:52
【问题描述】:

我有一张带有位置和设备名称的表格。我想保留组内匹配的设备名称部分。

location_code | device_name      | location
1               Building_1_in      Building_1
1               Building_1_out     Building_1
1               Building_1_gate    Building_1
2               Drive 3 gate2      Drive 3
2               Drive 3 gate1      Drive 3
2               Drive 3 keypad     Drive 3

我有位置代码和设备名称,但我正在尝试创建 location 列。我不能使用SUBSTRING 函数,因为目标字符串的长度不同,并且我不能使用CHARINDEX 函数,因为没有一致的分隔符。另外,location_code 太多,无法编写CASE WHEN 函数。

有人有什么想法吗?

【问题讨论】:

  • 可以肯定地说至少前两个词是组名吗?并且可以由任何字符分隔?最长的 device_name 是多少?
  • 不,位置名称有时多达五个字。有时空格分隔单词,有时是下划线。
  • 我想更多的样本
  • 我认为最好的解决方案是规范化这个表
  • 修改stackoverflow.com/questions/13864446/…中的逻辑得到你的答案。

标签: sql sql-server substring


【解决方案1】:

如果您按 location_code 对这些记录进行分组,那么 您可以通过

获得所需的结果

创建函数

Create FUNCTION dbo.getLocation
(
    @location_code int
)
RETURNS varchar(max)
AS
BEGIN

    declare @result varchar(max)

    declare @device_name1 varchar(max)
            ,@device_name2 varchar(max)
            ,@iterator int


    set @result = ''

    select top 1 @device_name1 = device_name from TableName where location_code = @location_code order by device_name
    select top 1 @device_name2 = device_name from TableName where location_code = @location_code order by device_name desc

    set @iterator = 1
    while(@iterator <= len(@device_name1) and @iterator <= len(@device_name2))
    begin

        if(SUBSTRING(@device_name1, @iterator, 1) = SUBSTRING(@device_name2, @iterator, 1))
        begin
            set @result = @result + SUBSTRING(@device_name1, @iterator, 1)
        end
        else
            break
        set @iterator = @iterator + 1
    end

    return @result

END
GO

并像使用它

select t.location_code, t.device_name, l.location
from TableName t
inner join (select location_code, dbo.getLocation(location_code) as location from TableName group by location_code) l on l.location_code = t.location_code

【讨论】:

    【解决方案2】:

    总体思路: 您可以按 location_code 和设备名称对表排序进行排序。然后,您可以为每个 location_code 提取第一个和最后一个的共同开始部分。

    【讨论】:

    • 你的想法帮助我改进了逻辑
    猜你喜欢
    • 2020-11-21
    • 1970-01-01
    • 2022-08-15
    • 1970-01-01
    • 2020-03-09
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    相关资源
    最近更新 更多