加入和重复行

时间:2015-05-29 15:11:21

标签: sql sql-server sql-server-2008

我需要为其他表中的值重复行。例如:

// Save the original rotation
OrgRotation = this.transform.rotation.eulerAngles;
rotation = OrgRotation;
// Do your stuff here
this.transform.rotation = Quaternion.Lerp(OrgRotation, Quaternion.Euler(rotation), 0.5f);

关于如何做到这一点的任何想法? 我为了简单而保持秩序,但它不需要按顺序排列;假设它是日期或varchar!

2 个答案:

答案 0 :(得分:6)

以下是一种方法:

SELECT Dept, Person, [Order]
FROM (SELECT Dept, Person,
            ROW_NUMBER() OVER (PARTITION BY Dept 
                               ORDER BY Person) AS rn,
            COUNT(*) OVER (PARTITION BY Dept) AS cnt
      FROM Dept ) t                            
CROSS JOIN [Order]
WHERE rn = ([Order] - 1) % cnt + 1
ORDER BY Dept, [Order], Person

这是某种强力解决方案:您获得OrderDept表之间的每一个组合,并使用窗口函数有选择地过滤此笛卡尔集合中的行

Demo here

编辑:(归功于@Giorgi)

使用简单的JOIN

可以实现相同的结果
SELECT Dept, Person, [Order]
FROM (SELECT Dept, Person,
            ROW_NUMBER() OVER (PARTITION BY Dept 
                               ORDER BY Person) AS rn,
            COUNT(*) OVER (PARTITION BY Dept) AS cnt
      FROM Dept ) t                            
INNER JOIN [Order] ON rn = ([Order] - 1) % cnt + 1
ORDER BY Dept, [Order], Person

后一种解决方案肯定更有效率。

Demo here

答案 1 :(得分:1)

这是另一个,我觉得也很有趣:

DECLARE @o TABLE ( id INT )
INSERT  INTO @o
VALUES  ( 1 ),( 2 ),( 3 ),( 4 ),( 5 ),( 6 )

DECLARE @d TABLE ( d CHAR(1), p CHAR(2) )
INSERT  INTO @d
VALUES  ( 'A', 'P1' ),
        ( 'A', 'P2' ),
        ( 'B', 'P3' ),
        ( 'B', 'P4' ),
        ( 'B', 'P5' ),
        ( 'C', 'P6' ),
        ( 'C', 'P7' ),
        ( 'C', 'P8' ),
        ( 'C', 'P9' )

;WITH cte1 AS(SELECT *, 
                     1 i1, 
                     (id - 1) % 2 + 1 i2, 
                     (id - 1) % 3 + 1 i3, 
                     (id - 1) % 4 + 1 i4, 
                     (id - 1) % 5 + 1 i5 
              FROM @o),
cte2 AS(SELECT *, 
               ROW_NUMBER() OVER(PARTITION BY d ORDER BY p) rn, 
               COUNT(*) OVER(PARTITION BY d) cn FROM @d)

SELECT c2.d, c2.p, c1.id 
FROM cte1 c1
JOIN cte2 c2 ON c2.rn = CASE c2.cn WHEN 1 THEN c1.i1
                                   WHEN 2 THEN c1.i2
                                   WHEN 3 THEN c1.i3
                                   WHEN 4 THEN c1.i4
                                   WHEN 5 THEN c1.i5
                                   WHEN 6 THEN c1.id
                        END                        
ORDER BY        c2.d, c1.id