使用subselect向视图添加更多列

时间:2018-11-07 18:43:11

标签: sql-server view sql-subselect

使用Microsoft SQL Server 2012,我试图创建一个新视图,当描述匹配时,该视图将返回行的真正开始和结束。

我有一张看起来像这样的桌子

+----+-------+-------+-----+
| ID | desc  | start | end | 
+----+-------+-------+-----+
|  1 | line1 |     0 | 100 |
|  2 | line2 |     0 | 100 |
|  3 | line2 |   101 | 200 | 
+----+-------+-------+-----+

我想再添加2列,以便当desc匹配时,它像这样从ID 2返回0,从ID 3返回200:

+----+-------+-------+-----+------------+----------+
| ID | desc  | start | end | real_start | real_end |
+----+-------+-------+-----+------------+----------+
|  1 | line1 |     0 | 100 |          0 |      100 |
|  2 | line2 |     0 | 100 |          0 |      200 |
|  3 | line2 |   101 | 200 |          0 |      200 |
+----+-------+-------+-----+------------+----------+

到目前为止我的语法:

CREATE VIEW tableview1 
AS 
     SELECT 
         ID, desc,
         start, end,
         (???) as real_start,
         (???) as real_end 
     FROM 
         linetable 
     WHERE 
         condition;

当描述匹配并选择两者中的最低者时,我不知道如何分组和比较这两行。我将自己玩耍并更新线程。

非常感谢!

2 个答案:

答案 0 :(得分:0)

对于该desc,您的子选择可能只是MIN()/ MAX()

答案 1 :(得分:0)

我认为这行得通,有人可以确认吗?

    CREATE VIEW tableview1 
AS 
     select 
     t1.ID, t1.desc,
     t1.start, t1.end,
     (select min(start)
        from linetable z
        where z.desc = t1.desc) as real_start,
     (select min(end)
        from linetable z
        where z.desc = t1.desc) as real_end
     from    
     (SELECT 
         ID, desc,
         start, end,
     FROM 
         linetable 
     WHERE 
         condition) as t1