简体   繁体   中英

SQL Server: Multiply a result row

I have several result rows from a SELECT query.

SELECT a.code, CONCAT('text output', a.result)
FROM table1 a

Result looks like

code |  text
a    | 'text output a'
b    | 'text output b'

One column contains concatenated text output. I simply want to have each result row duplicated with slightly different text outputs (which can be hardcoded).

The expected result should be like

code |  text
a    | 'example 1: text output a'
a    | 'example 2: text output a'
b    | 'example 1: text output b'
b    | 'example 2: text output b'

In essence, I want - for each result - to put example 1 and example 2 in front. How can this be done efficiently?

Probably the easiest way in your case is following:

SELECT a.code, CONCAT('example 1: text output', a.result)
FROM table1 a
union all
SELECT a.code, CONCAT('example 2: text output', a.result)
FROM table1 a

This can be done with recursive query

DECLARE @table TABLE(
    code CHAR(1)
    , txt VARCHAR(20)
)

INSERT INTO @table VALUES 
('a', 'text output a')
,('b', 'text output b')
,('c', 'text output c')

;WITH q1 AS(
    SELECT 1 ex, tbl1.code, tbl1.txt
    FROM @table tbl1
        UNION ALL
            SELECT ex+1, q1.code, q1.txt 
            FROM q1
            WHERE q1.ex < 3
)
SELECT q1.code, concat('Example ', q1.ex, ': ', q1.txt) [text]
FROM q1
ORDER BY q1.code, q1.ex

you can change number 3 according how many times you want each row to be displayed

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