如何在SQL中进行字符串转换?

时间:2017-08-08 14:02:59

标签: sql-server

假设该表格如下所示

ID  |    Freq0    |     Freq1    | is_overnight | start_time |  end_time  |
---------------------------------------------------------------------------
1   |   _23_5_7   |    _2____7   |       Y      |    1:00    |    3:00    |
2   |   1_____7   |    1______   |       N      |    5:00    |    7:00    |
3   |   _2__5__   |    _2_____   |       N      |    23:00   |    1:00    |

其中Freq0Freq1表示事件ID的出现。例如,Freq0 = 1_____7表示事件发生在星期一和星期日。此外,Freq0Freq1都是varchar(7)

修改逻辑是is_overnight = Y or start_time > end_timeFreq0Freq1都需要右移,否则没有变化。

右移的例子是

_23_5_7 => 1_34_6_
1_____7 => 12_____
_2__5__ => __3__6_

将此逻辑应用于上表,我们应该得到以下结果

ID  |    Freq0    |     Freq1    | is_overnight | start_time |  end_time  |
---------------------------------------------------------------------------
1   |   1_34_6_   |    1_3____   |       Y      |    1:00    |    3:00    |
2   |   1_____7   |    1______   |       N      |    5:00    |    7:00    |
3   |   __3__6_   |    __3____   |       N      |    23:00   |    1:00    |

我能够使用Python完成此任务,如下所示:

def right_shift(column_name):
    def helper(raw_data):
        content = raw_data[column_name]
        if raw_data['is_overnight '] == 'Y' or raw_data['start_time '] > raw_data['end_time  ']:
            content = content[-1] + content[:-1]
            content = [str(index + 1)  if content[index] != '_' else '_' for index in range(len(content))]
            return "".join(content)
        else:
            return content
    return helper

raw_data = pd.read_sql(sql_query, connection)
raw_data['Freq0'] = raw_data.apply(right_shift('Freq0'), axis = 1)
raw_data['Freq1'] = raw_data.apply(right_shift('Freq1'), axis = 1)

但后来我被要求在sql中完成此操作,这时我遇到了将其写入一段优雅代码时遇到的困难。有人能帮我一把吗?

1 个答案:

答案 0 :(得分:0)

一个选项,不优雅,但似乎有效

示例

checkout([$class: 'GitSCM',
         branches: [[name: "${params.prop1}"]],
         userRemoteConfigs: [[url: 'https://github.com/path/to/repo', 
                              credentialsId: 'xxx']]
         ])

<强>返回

Declare @YourTable table (Freq0 varchar(7))
Insert Into @YourTable values
 ('_23_5_7')  -- => 1_34_6_
,('1_____7')  -- => 12_____
,('_2__5__')  -- => __3__6_

Select *
      ,NewVal = concat( IIF(Substring(Freq0,7,1)='_','_','1')
                       ,IIF(Substring(Freq0,1,1)='_','_','2')
                       ,IIF(Substring(Freq0,2,1)='_','_','3')
                       ,IIF(Substring(Freq0,3,1)='_','_','4')
                       ,IIF(Substring(Freq0,4,1)='_','_','5')
                       ,IIF(Substring(Freq0,5,1)='_','_','6')
                       ,IIF(Substring(Freq0,6,1)='_','_','7')
                      )

 From @YourTable A