[英]SQL Server: Multiply a result row
我有幾個來自SELECT
查詢的結果行。
SELECT a.code, CONCAT('text output', a.result)
FROM table1 a
結果看起來像
code | text
a | 'text output a'
b | 'text output b'
一列包含連接的文本輸出。 我只是想讓每個結果行都與文本輸出略有不同(可以硬編碼)重復。
預期結果應該像
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'
本質上,我希望-對於每個結果-將示例1和示例2放在前面。 如何有效地做到這一點?
在您的情況下,最簡單的方法可能是:
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
這可以通過遞歸查詢來完成
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
您可以根據希望每行顯示多少次來更改數字3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.