1

我有一个需要设置条件的 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
的情况下将精选列设为真。如果视频计数大于 1,则将所有精选列标记为假,然后将观看次数最多的 5 个视频设为精选。

数据库是 SQL Server。

谢谢,

4

4 回答 4

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
于 2012-12-24T09:19:33.130 回答
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
于 2012-12-24T09:35:40.617 回答
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
于 2012-12-24T09:18:49.370 回答
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 个观看的视频中,所以不需要特殊情况。

SQL Fiddle 上的实时示例。

于 2012-12-24T09:38:12.887 回答