在我的应用程序中,有几个地方向用户显示一组随机的X项.UI要求显示正好X项.但是,无法保证表中会有X项.所以,如果没有X项,我需要用随机副本填充结果.
我需要写一个基本上是的查询:
SELECT TOP(@count) *
FROM Things
ORDER BY NEWID()
Run Code Online (Sandbox Code Playgroud)
我希望能够向SQL询问X记录,并且每次都能获得准确的X记录.有没有一种简单的方法可以在SQL中完成此任务?
谢谢.
好吧,我有一个解决方案,但我仍然认为这些要求是荒谬的.这假设源表(在我的情况下@t)至少有一行.如果你有零行,你究竟在演示什么?
DECLARE @count INT = 17; -- here is whatever your 'X' is; pick any value
DECLARE @t TABLE(i INT);
-- just insert 10 arbitrary values; test with @count = 5, @count = 247, etc.
INSERT @t VALUES(150),(170),(50),(100),(200),(230),(20),(800),(180),(632);
DECLARE @x INT; SELECT @x = COUNT(*) FROM @t;
SELECT TOP (@count) x.* FROM
(
-- limit this set to @count:
SELECT TOP (@count) * FROM @t ORDER BY NEWID()
) AS x
OUTER APPLY
(
-- limit this set the ratio of @count to rows in @t
-- add one to round up for integer division:
SELECT TOP (@count/@x+1) * FROM sys.all_objects
WHERE @count > @x -- only evaluate this subquery if we don't have enough rows
) AS y
ORDER BY NEWID(); -- need a 2nd ORDER BY in my tests to avoid pockets of same values
Run Code Online (Sandbox Code Playgroud)