生成从 1 到特定值的数据

Generate data from 1 to specific value(生成从 1 到特定值的数据)
本文介绍了生成从 1 到特定值的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要生成这样的结果假设我有这些记录

I am going to generate a result like this suppose I have this records

Salah 3
John  2

我会期待这个

Salah
Salah
Salah
John
John

推荐答案

一种方法,如果您总是对 n 使用 small 值,则使用 rCTE:

One method, if you always have a small value for n is to use a rCTE:

WITH rCTE AS(
    SELECT [Name],
           N,
           1 AS I
    FROM dbo.YourTable
    UNION ALL
    SELECT [Name],
           N,
           I + 1
    FROM rCTE
    WHERE I < N)
SELECT [Name]
FROM rCTe
ORDER BY [Name] DESC;

如果您有更大的数字,请使用性能更好的 Tally.我在这里使用内联:

If you have much larger numbers, use a more performamt Tally. I use an inline here:

WITH N AS(
    SELECT N
    FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N(N)),
Tally AS(
    SELECT --TOP (SELECT MAX(N) FROM dbo.YourTable) --Limits the number of rows, which could also provide a performance benefit if you only sometimes have large numbers
           ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS I
    FROM N N1, N N2, N N3) --1000 rows, add more cross joins for more rows
SELECT [Name]
FROM dbo.YourTable YT
     JOIN Tally T ON YT.N >= T.I
ORDER BY YT.[Name] DESC;

db<>fiddle

这篇关于生成从 1 到特定值的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)