条件SQL查询

时间:2012-12-24 09:15:16

标签: sql sql-server database

我有一个需要进行条件化的SQL查询,这是我目前的SQL查询:

-- IF the video count is 1
    UPDATE tbl_Video SET
    [Featured] = 1
    WHERE [VideoId] = 1
    GO
-- ELSE IF Video Count is greater than 1
    UPDATE tbl_Video SET
    [Featured] = 0
    WHERE [Featured] = 1
    GO
    -- Set the top 5 viewed videos as featured as default
    UPDATE tbl_Video SET
    [Featured] = 1
    WHERE VideoId In (SELECT TOP 5 VideoId FROM tbl_Video
    ORDER BY Views DESC)
    GO
-- END

希望上面查询中的注释能够解释我想要实现的目标,方案是:

  

如果视频数为1,则在视频ID = 1的情况下将特色列设为true   如果视频数量大于1,则将所有精选列标记为false,然后将前5个已观看视频视为精选视频。

数据库是SQL Server。

谢谢,

4 个答案:

答案 0 :(得分:2)

如果这是在sql server程序中你可以这样做:

declare @videoCount integer

--this is just a guess at what video count is
select @videoCount = count(*) from tbl_video

if (@videoCount = 1)
    UPDATE tbl_Video SET
    [Featured] = 1
    WHERE [VideoId] = 1
ELSE IF (@videoCount > 1)
BEGIN
    UPDATE tbl_Video SET
    [Featured] = 0
    WHERE [Featured] = 1

    UPDATE tbl_Video SET
    [Featured] = 1
    WHERE VideoId In (SELECT TOP 5 VideoId FROM tbl_Video ORDER BY Views DESC)
END

答案 1 :(得分:1)

如果您已经拥有@videoCount

not null变量
--Using case
update tbl_Video SET
    [Featured] = case when @videoCount = 1 then 0 
                      when @videoCount > 0 end --else [Featured] end
where [VideoId] = 1

--Using cte
;with cte as 
(
    select top (5) * 
    from tbl_Video
    order by Views desc
)
update cte set [Featured] = 1

答案 2 :(得分:0)

DECLARE @VideoCount INT

SELECT @VideoCount = COUNT(*) FROM tbl_Video

IF @VideoCount = 1
BEGIN
   UPDATE tbl_Video SET
   [Featured] = 1
    WHERE [VideoId] = 1
   GO
END
ELSE IF @VideoCount > 1
BEGIN
   UPDATE tbl_Video SET
   [Featured] = 0
   WHERE [Featured] = 1
   GO
END

答案 3 :(得分:0)

您可以在一个查询中执行此操作:

update  tv
set     Featured = case when rn <= 5 then 1 else 0 end
from    (
        select  row_number() over (order by ViewCount desc) as rn
        ,       *
        from    tbl_Video
        ) tv

如果只有一个视频,它必须位于前5个观看过的视频中,因此不需要特殊情况。

Live example at SQL Fiddle.