如何使用子字符串查找最大字符

时间:2019-04-17 14:58:21

标签: sql sql-server case sql-like sql-server-2016

这应该相对容易。我以求偿数据为生。我有以下假设的ClaimID:17060C048388A3

关于这一点,是第14个字符空间中的A代表“调整”,下面的数字表示已经调整了时间。因此,例如,此特定声明已进行了3次调整。 不幸的是ClaimID 17060C048388A1、17060C048388A2和17060C048388A3(所有三个调整都显示)。在计算这些索赔时,我如何只选择最高的调整以避免重复。并非所有声明都经过调整,因此它们都没有A,也不是全部15个字符。

所以我认为我需要按如下所述开始一个案例声明:

SELECT DISTINCT TOP 10000 *,
    CASE WHEN CLAIMID LIKE '%A%' THEN ??????

如果在ClaimID中有“ A”,那么任何建议都应抓住ClaimID中“ A”之后的下一个最高位。因此,如果索赔要求有8个调整项,那么我只想查看以A8结尾的一项。

预先感谢大家, 格雷格

4 个答案:

答案 0 :(得分:0)

我再次查看了您的问题,并创建了以下解决方案:

import csv 

df.to_csv("my_temp_csv.csv")

with open('my_temp_csv.csv', 'rb') as infile, open('my_final_csv.csv', 'wb') as outfile:
    reader = csv.reader(infile)
    header = reader.next()
    new_header = []
    for element in header:
        if element not in new_header:
            new_header.append(element)
        else:
            new_header.append("")

    w = csv.writer(outfile)
    w.writerow(new_header)

    for row in reader:
        w.writerow(row)

demo on dbfiddle.uk

答案 1 :(得分:0)

这将更简单;

select * from Table1 where
regexp_like("column1",substr("column1",1,instr("column1",'A'))||
            (select max(substr("column1",-1)) from Table1) );`

检查此:http://sqlfiddle.com/#!4/cb16f/7

答案 2 :(得分:0)

具有CTE:

with cte as(
  select
    claimid,
    case 
      when claimid like '%A%' then left(claimid, charindex('A', claimid) - 1) 
      else claimid
    end claim,
    case 
      when claimid like '%A%' then cast(right(claimid, len(claimid) - charindex('A', claimid)) as int)
      else 0
    end adjustment
  from tablename
)
select distinct top 10000 t.* 
from tablename t inner join (
  select 
    claim + 
    case max(adjustment) 
      when 0 then ''
      else 'A' + cast(max(adjustment) as varchar(10))
    end claimid 
  from cte
  group by claim
) g on g.claimid = t.claimid

请参见demo
对于此示例数据:

> claimid        | value
> :------------- | :----
> 17060C048388A1 | a    
> 17060C048388A2 | b    
> 17060C04838811 | c    
> 17060C04838866 | d    
> 17060C04838855 | e    
> 17060C048388A3 | f    
> 17060C04838899 | g 

结果是:

> claimid        | value
> :------------- | :----
> 17060C04838811 | c    
> 17060C04838866 | d    
> 17060C04838855 | e    
> 17060C048388A3 | f    
> 17060C04838899 | g 

答案 3 :(得分:0)

这对我有用(假设我没有发现任何错误)。我从所有评论中选取了示例,并将它们放在一起,所以谢谢所有回答。

SELECT DISTINCT SUBSTRING(CLAIMID, 1,13) + MAX(RIGHT(CLAIMID, 2)) AS 
MAX_CLAIM_ADJUSTMENT
FROM LA_TEMP.DBO.ITEM19
WHERE (SUBSTRING(CLAIMID, 14, 1) = 'A'
OR SUBSTRING(CLAIMID, 13, 1) = 'A')
GROUP BY left(CLAIMID, 13)
UNION
SELECT DISTINCT SUBSTRING(CLAIMID, 1,14) + MAX(RIGHT(CLAIMID, 1)) AS 
MAX_CLAIM_ADJUSTMENT
FROM LA_TEMP.DBO.ITEM19
WHERE (SUBSTRING(CLAIMID, 15, 1) = 'A'
OR SUBSTRING(CLAIMID, 14, 1) = 'A')
GROUP BY left(CLAIMID, 14)
ORDER BY MAX_CLAIM_ADJUSTMENT

我注意到A可以是第13个字符或第14个字符。