Sql server 基于现有行在表中生成行
是否可以基于SQL Server中表中的现有列在表中生成行?例如,如果Sql server 基于现有行在表中生成行,sql-server,tsql,Sql Server,Tsql,是否可以基于SQL Server中表中的现有列在表中生成行?例如,如果RunDatesvalue=31/01/2020和RunTimes=3,则RunDate=31/01/2020 当前表 所需表格 首先,您需要理货表(视图),例如 然后你把它放在桌子上 declare @MyTable table (MyDate date, RunCount int); insert into @MyTable (MyDate, RunCount) values ('31 Jan 2020', 3
RunDates
value=31/01/2020
和RunTimes=3
,则RunDate=31/01/2020
当前表
所需表格
首先,您需要理货表(视图),例如 然后你把它放在桌子上
declare @MyTable table (MyDate date, RunCount int);
insert into @MyTable (MyDate, RunCount)
values
('31 Jan 2020', 3),
('29 Feb 2020', 2),
('31 Mar 2020', 1);
select MT.*
from @MyTable MT
inner join cteTally T on T.N <= MT.RunCount
order by MyDate, RunCount;
注:理货表由@Larnu提供,但我找不到原始帖子。首先,您需要理货表(视图),例如 然后你把它放在桌子上
declare @MyTable table (MyDate date, RunCount int);
insert into @MyTable (MyDate, RunCount)
values
('31 Jan 2020', 3),
('29 Feb 2020', 2),
('31 Mar 2020', 1);
select MT.*
from @MyTable MT
inner join cteTally T on T.N <= MT.RunCount
order by MyDate, RunCount;
注:理货表由@Larnu提供,但我找不到原始帖子。您可以使用递归CTE进行操作:
with cte as (
select RunDates, RunTimes, 1 nr from tablename
union all
select RunDates, RunTimes, nr + 1
from cte
where nr < RunTimes
)
select RunDates, RunTimes from cte
order by RunDates
您可以使用递归CTE执行此操作:
with cte as (
select RunDates, RunTimes, 1 nr from tablename
union all
select RunDates, RunTimes, nr + 1
from cte
where nr < RunTimes
)
select RunDates, RunTimes from cte
order by RunDates
通过从
sys.objects
创建序列号,可以尝试以下内部联接
这里我修正了10
假设RunTime
的最大值。您可以创建一个变量并指定运行时值的最大值
并使用该变量代替10
这里有一个方法可以做到这一点
create table SampleTable (DtDate Date, RunTimes int)
insert into SampleTable Values
('31 Jan 2020', 3),
('29 Feb 2020', 2),
('31 Mar 2020', 1)
SELECT SampleTable.*
FROM SampleTable
INNER JOIN (
SELECT TOP 10 ROW_NUMBER() OVER (
ORDER BY object_id
) AS SrNo
FROM sys.objects
) mst ON RunTimes >= SrNo
ORDER BY DtDate
现场演示。您可以通过从sys.objects
创建序列号来尝试以下内部连接
这里我修正了10
假设RunTime
的最大值。您可以创建一个变量并指定运行时值的最大值
并使用该变量代替10
这里有一个方法可以做到这一点
create table SampleTable (DtDate Date, RunTimes int)
insert into SampleTable Values
('31 Jan 2020', 3),
('29 Feb 2020', 2),
('31 Mar 2020', 1)
SELECT SampleTable.*
FROM SampleTable
INNER JOIN (
SELECT TOP 10 ROW_NUMBER() OVER (
ORDER BY object_id
) AS SrNo
FROM sys.objects
) mst ON RunTimes >= SrNo
ORDER BY DtDate
现场演示