我已经在这里看到了这篇文章(http://stackoverflow.com/questions/1398113/sql-select-one-row-randomly-but-taking-into-account-a-weight),但无法解决。我应该把“东西”表放在哪里?他们为什么不使用 NEWID() 而不是 RND()?
餐桌用品
id item weight location
1 ball 1 Wyoming
2 cup 2 Alaska
3 sock 1 Idaho
4 car 3 Miami
5 hot girl 5 Brazil
现在根据上面引用的那篇文章,我应该这样做
SELECT TOP 1 t.*
FROM @Table t
INNER JOIN (SELECT t.id, sum(tt.weight) AS cum_weight
FROM @Table t
INNER JOIN @Table tt ON tt.id <= t.id
GROUP BY t.id) tc
ON tc.id = t.id,
(SELECT SUM(weight) AS total_weight FROM @Table) tt,
(SELECT RAND() AS rnd) r
WHERE r.rnd * tt.total_weight <= tc.cum_weight
ORDER BY t.id ASC
我想做上面的事情,但是以这种方式:
SELECT TOP (1) from stuff WHERE blahblahblah AND (location='Brazil' OR location='Wyoming' OR location='Brazil') AND (weight <= cum_weight) ORDER BY NEWID()
我只是猜测我可以使用 NEWID() 而不是被迫使用 RND()