[英]Return a row of data mutiple times if a value in a column is greater than 1 in SQL
I have a table of data which is shown below:我有一个数据表,如下所示:
I need to select all the data back but if the 'Entries' Column is greater than 1 then it should show that many times in my results.我需要选择所有数据,但如果“条目”列大于 1,那么它应该在我的结果中多次显示。
I am unsure on how or even if this is possible to do, could someone please steer me in the right direction?我不确定如何或即使这是可能的,有人可以引导我朝着正确的方向前进吗?
The results should look like the below:结果应如下所示:
One simple method uses a recursive CTE:一种简单的方法使用递归 CTE:
with cte as (
select id, entries, date, postcode, 1 as n
from t
union all
select id, entries, date, postcode, n + 1
from cte
where n <= entries
)
select id, entries, date, postcode
from cte;
Note: If entries
could be larger than 100, you need to add option (maxrecursion 0)
.注意:如果entries
可能大于 100,则需要添加option (maxrecursion 0)
。
One option joins the table with a list of numbers:一个选项将表格与数字列表连接起来:
select t.*
from mytable t
inner join (
select 1 n union select 2 union all select 3 union all select 4 union all select 5
) x on x.n <= t.entries
This query would handle up to 5 repeatition for each records.此查询最多可为每条记录处理 5 次重复。 If you need to handle more, then you can either:如果您需要处理更多,那么您可以:
row_number()
against a large table通过对大表使用row_number()
生成数字表You have tagged with T-SQL, a simple and recursion free way would be to use Cross Apply.您已使用 T-SQL 进行标记,一种简单且无递归的方法是使用 Cross Apply。 ie: IE:
DECLARE @f TABLE (id INT, Entries INT, [Date] DATE, postcode VARCHAR(10));
INSERT INTO @f
(id,Entries,Date,postcode)
VALUES
(1,2,'20191217','SG14LJ'),
(2,2,'20191217','SG14LJ'),
(3,1,'20191217','SG14LJ'),
(4,1,'20191217','SG14LJ'),
(5,1,'20191217','SG14LJ'),
(6,1,'20191217','SG14LJ'),
(7,1,'20191217','SG14LJ'),
(8,1,'20191217','SG14LJ'),
(9,2,'20191217','SG14LJ'),
(10,3,'20191217','SG14LJ');
WITH cteTally AS
(
SELECT TOP (SELECT MAX(entries) FROM @f)
ROW_NUMBER() OVER (ORDER BY t1.Object_ID) AS N
FROM Master.sys.All_Columns t1
CROSS JOIN Master.sys.All_Columns t2
)
SELECT f.*
FROM @f f
CROSS APPLY (SELECT TOP(f.Entries) N FROM cteTally) t(n);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.