DYNAMICALLY重复SELECT查询结果

时间:2015-09-04 08:34:32

标签: sql-server

这是我的疑问:

SELECT Barcode 
FROM Table_Barcode
WHERE IdArticle = 'Ar-1029344'

结果是这样的:

BarCode
-------
5142589
0123454
1111145

我想复制每个寄存器,例如,4次就像这样:

BarCode
-------
5142589
5142589
5142589
5142589
0123454
0123454
0123454
0123454
1111145
1111145
1111145
1111145

修改

我需要动态,因为将来我不知道我是否需要 复制寄存器4次或10或25次

3 个答案:

答案 0 :(得分:4)

使用CROSS JOIN:

<强> SqlFiddleDemo

SELECT t.Barcode
FROM Table_Barcode t
CROSS JOIN (VALUES (1), (2), (3), (4)) AS tab(col)
WHERE t.IdArticle = 'Ar-1029344'

具有可变重复的第二个版本:

DECLARE @rep INT = 5;  /* How many times should be repated */

WITH cte AS
(
   SELECT TOP (@rep)
        ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS N
   FROM sys.All_Columns ac1         /* You can use any table to populate */
   CROSS JOIN sys.ALL_Columns ac2   /* You can use any table to populate */
)
SELECT t.BarCode
FROM TABLE_BARCODE t
CROSS JOIN cte
ORDER BY t.BarCode;

或者,如果您知道最大重复次数,则可以对以下值进行硬编码:

DECLARE @rep INT = 5;  /* How many times should be repated */

WITH cte AS
(
   SELECT TOP(@rep) col
   FROM (VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10)
                (11), (12), (13), (14), (15), (16), (17), (18), (19), (20)
                (21), (22), (23), (24), (25)) AS tab(col)
)
SELECT t.BarCode
FROM TABLE_BARCODE t
CROSS JOIN cte;

答案 1 :(得分:2)

如果您只想让每一行出现四次(无论出于何种原因),您可以执行以下操作:

select Barcode
from Table_Barcode
cross join (select 1 union all select 2 union all
            select 3 union all select 4) Num(n)
where IdArticle = 'Ar-1029344'

对于更复杂的查询,您可能需要考虑在数据库中添加一个数字表 - 这只是一个包含每个整数值的表。这允许您将来编写这样的查询,而无需手动输入您想要的数字 - 您只需JOIN到数字表并使用ONWHERE子句适当地过滤它。

答案 2 :(得分:1)

您可以使用UNION ALL连接查询结果。例如:

select Barcode
from Table_Barcode
where IdArticle = 'Ar-1029344'
union all
select Barcode
from Table_Barcode
where IdArticle = 'Ar-1029344'
union all
select Barcode
from Table_Barcode
where IdArticle = 'Ar-1029344'
union all
select Barcode
from Table_Barcode
where IdArticle = 'Ar-1029344'

但是,根据您想要如何使用查询结果,在显示层中显示每行4次而不是从服务器检索冗余数据是不是更有意义?