从两个表联合生成自动id

时间:2017-09-01 18:21:16

标签: sql sql-server

我有两个表:组合活动和简单活动:

composed_activities

id | name    
1  | Activity 1    
5  | Activity 2

simple_activities

id | name    
1  | S Activity 1    
2  | S Activity 2    
3  | S Activity 3

我需要一个返回新生成ID的查询,带有'+'前缀的组合活动和带有' - '前缀的简单活动:

id | name

1  | + Activity 1    
2  | + Activity 5    
3  | - S Activity 1    
4  | - S Activity 2    
5  | - S Activity 3

到目前为止,我只设法加入两个表,但不会自动生成ID:

SELECT id, CONCAT('- ',name) as name 
FROM simple_activities 
UNION 
SELECT id,CONCAT('+ ',name) AS name 
FROM composed_activities

有人可以告诉我如何生成ID吗?提前谢谢。

2 个答案:

答案 0 :(得分:3)

将您的联合包装到子查询中,然后使用ROW_NUMBER()窗口函数生成您的ID:

SELECT 
    ROW_NUMBER() OVER (ORDER BY name ASC) as newid, 
    id as oldid, 
    name
FROM 
    (SELECT 
        id, 
        CONCAT('- ',name) as name 
     FROM simple_activities 
     UNION 
     SELECT 
        id,
        CONCAT('+ ',name) AS name 
     FROM composed_activities) subquery

答案 1 :(得分:1)

JNevill是正确的,是正确的答案,代码更少。

我使用CTE发帖,因为我发现它们更容易阅读:

DECLARE @composed_activities TABLE (id int, name varchar(20))
INSERT INTO @composed_activities (id, name)
VALUES (1,'Activity 1'), (5,'Activity 2')

DECLARE @simple_activities TABLE (id int, name varchar(20))
INSERT INTO @simple_activities (id, name)
VALUES (1,'S Activity 1'), (2,' S Activity 2'), (3,' S Activity 3')

;WITH X (id, name) AS 
(
    SELECT id,'+ '+name FROM @composed_activities
    UNION ALL
    SELECT id,'- '+name FROM @simple_activities
), Y AS
    (
        SELECT ROW_NUMBER() OVER(ORDER BY name,id) AS id, name
        FROM X
    )

SELECT * 
FROM Y