简体   繁体   中英

Concatenate calculated fields in SQL

I have 3 columns that are string columns calculated using complex substring and replace functions.

I have a 4th column which should be col1 + col2 + col3.

At the moment the 4th column is repeating the calculations required to computed col1 and col2 and col3.

The select statement looks something like this (I've removed most of the functions):

select 
STR(c1, 2, 0) as col1,
STR(c2, 2, 0) as col2,
STR(c3, 2, 0) as col3,
STR(c1, 2, 0) + STR(c2, 2, 0) + STR(c3, 2, 0) as col4
from blah

The issue is that we're repeating the functions to calculate the columns, breaking the DRY principal and opening an opportunity for errors to creep in.

I'd prefer if we could do something like this:

select 
STR(c1, 2, 0) as col1,
STR(c2, 2, 0) as col2,
STR(c3, 2, 0) as col3,
col1 + col2 + col3 as col4
from blah

Is there a neat way of doing this? I think it could be done using a temp table but that seems like overkill.

Is it worth doing, or am I just taking DRY to seriously.

You can do this with a CTE:

;WITH data_cte (col1, col2, col3)
AS 
(
    select 
        STR(c1, 2, 0) as col1,
        STR(c2, 2, 0) as col2,
        STR(c3, 2, 0) as col3
    from blah
)

SELECT
    col1, col2, col3,
    col1 + col2 + col3 as col4
FROM data_cte

You can do it like this (sorry about formatting):

select i.col1, i.col2, i.col3, i.col1 + i.col2 + i.col3 as col4
from (
    select 
    STR(c1, 2, 0) as col1,
    STR(c2, 2, 0) as col2,
    STR(c3, 2, 0) as col3,
    from blah ) i

This is another solution (but I admit, I'd prefer DavidG's CTE approach (+1 from my side).

Just to show, that you need some kind of sub select to give you columns names you can work with:

SELECT col1,col2,col3,col4 
FROM
(
    SELECT STR(c1, 2, 0) as col1,
           STR(c2, 2, 0) as col2,
           STR(c3, 2, 0) as col3
    FROM @tbl
) AS tbl
CROSS APPLY(SELECT col1 + col2 + col3) as ThisIs(col4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM