根据频率重复行

问题描述 投票:-2回答:4

我有一个有两列名为AB的表,定义如下:

A   B
c1  2
c2  3
c3  4

预期的产出是:

A     B
c1    1
c1    2  
c2    1
c2    2
c2    3
c3    1
c3    2
c3    3
c3    4
sql sql-server self-join
4个回答
1
投票
CREATE TABLE #table2
    ([A] varchar(2), [B] int)
;

INSERT INTO #table2
    ([A], [B])
VALUES
    ('c1', 2),
    ('c2', 3),
    ('c3', 4)

;WITH nums AS
       (SELECT 1 AS value ,a,b from #table2
        UNION ALL
        SELECT value + 1  AS value  ,A,b
        FROM nums
        WHERE nums.value <B)
    SELECT a,value
    FROM nums order by a,value

产量

a   value
c1  1
c1  2
c2  1
c2  2
c2  3
c3  1
c3  2
c3  3
c3  4

0
投票

创建了一个Table值函数,其中我使用Recursive cte来计算put中给定的重复值然后使用Cross Apply将函数加入表中

CREATE FUNCTION [dbo].[udf_GetData] (
    @Data INT
    )
RETURNS @output TABLE (
    Data INT

    )

BEGIN       
        ;WITH CTe
        AS
        (
            SELECT 1 As Data 
            UNION ALL
            SELECT Data+1
            FROM CTe
            WHERE Data < @Data
        )
        INSERT INTO @output
        SELECT Data FROM CTe

    RETURN
END

示例数据和解释如何使用CROSS APPLY调用函数

 DECLARE @Data AS TABLE (A VARCHAR(10),B INT)
    INSERT INTO @Data

    SELECT 'c1',  2 UNION ALL
    SELECT 'c2',  3 UNION ALL
    SELECT 'c3',  4

    SELECT d.A,
    (SELECT [dbo].[udf_GetData](d.B)) AS RecData
    FROM @Data d

结果

A   RecursiveData
----------------
c1      1
c1      2
c2      1
c2      2
c2      3
c3      1
c3      2
c3      3
c3      4

0
投票

你可以试试这个:

// test data
declare @tbl table(A char(2),  B int);
insert into @tbl values
('c1',  2),
('c2',  3),
('c3',  4);
// create CTE with numbers which we will need to join
declare @max int;
select @max = max(B) from @tbl;
;with numbers as (
    select 1 n
    union all
    select n + 1 from numbers
    where n < @max
)
// join numbers with your table
select A, n from @tbl t
join numbers n on t.B >= n.n 
order by A, n

0
投票

说,你的表名是测试。

WITH r(a, b, repeat) as 
(SELECT a, b, 1 from test
union all
select a, b, repeat+1 from  r
where r.repeat < r.b)
select * from r
ORDER BY a, repeat;
© www.soinside.com 2019 - 2024. All rights reserved.