使用where子句创建带有计算列的视图

时间:2019-03-22 17:17:48

标签: sql

我想通过对相应列的值为特定值的列执行简单的数学运算,将计算列添加至视图。例如:

CREATE VIEW v_tracks 
AS 
SELECT
    (trackid + 1) as calcTrackId Where name like "WuTang",
    tracks.name,
    albums.Title AS album,
    media_types.Name AS media,
    genres.Name AS genres
FROM
    tracks
INNER JOIN albums ON Albums.AlbumId = tracks.AlbumId
INNER JOIN media_types ON media_types.MediaTypeId = tracks.MediaTypeId
INNER JOIN genres ON genres.GenreId = tracks.GenreId;

但是,这不起作用。我只想在名称(引用视图中的name列)为“ WuTang”时将轨道ID递增1。我该怎么办?

2 个答案:

答案 0 :(得分:2)

由于您不确定是否列出了SQL技术,但这应该可以(或根据技术使用类似的语法)

(case when name = 'WuTang'
      then row_number() over (partition by name order by ?)
 end) as calcTrackId 

答案 1 :(得分:0)

这是您想要的吗?

?

name应该与您关心的顺序相对应。如果您不在意,可以随时使用NULL

这将为每个WuTang轨道分配一个增量值,为其他sum(case when name = 'WuTang' then 1 else 0 end) over (partition by name order by ?) as calcTrackId 分配一个增量值。

如果您希望增量值不仅出现在WuTang行中,而且出现在所有行中,那么请使用累积总和:

SELECT
    table_A.Unit,
    ISNULL(Table_B.Value1, table_A.Value1) AS [Value1],
    ISNULL(Table_B.Value2, table_A.Value2) AS [Value2],
    etc ..
FROM table_A
LEFT OUTER JOIN Table_B ON Table_B.Unit = Table_A.Unit