添加修剪过的子串

问题描述

使用sql server:

我有许多修剪 txt 文件的命令,例如:

Case when charindex('-',Substring([RawStreamOut],179,10)) > 0   
                then '-' + Replace(LTrim(RTRIM(Substring([RawStreamOut],9))),','')  else
                        LTrim(RTRIM(Substring([RawStreamOut],10))) end as [Days_Old_16_To_20],Case when charindex('-',196,10))) end as [Days_Old_21_To_40]

等等...

我有很多这样的。

电流输出

i need the total value column to do a calculation of all my days old columns

我需要能够将这些命令的结果添加到名为“total”的新列中。有没有简单的方法可以做到这一点?

解决方法

你现在拥有的是:

select 
    case when charindex........as [Days_Old_16_To_20],.......
from
    (bunch of tables and joins)

相反,将您的公式放在交叉应用中:

select
    q.*
from 
    (bunch of tables and joins)
    cross apply
    ( select
        case when charindex........as [Days_Old_16_To_20],.......
    ) as q

现在您可以向您的选择中添加一个新列:

select
    q.[Days_Old_16_To_20] + q.[Days_Old_21_To_40] + .... as [Total_value],q.*
from 
    (bunch of tables and joins)
    cross apply
    ( select
        case when charindex........as [Days_Old_16_To_20],.......
    ) as q
,

一种简单的方法是使用 view

创建视图 SomeView 为

select...
Case when charindex('-',Substring([RawStreamOut],179,10)) ..... end as [Days_Old_16_To_20],Case when charindex('-',196,10)) ..... end as [Days_Old_21_To_40]
.
.
from <tables>

那么您的查询可以简单地

select 
    column,[Days_Old_16_To_20] + [Days_Old_21_To_40] +... as total_Value
from someView