我正在使用SQL Server 2012,并且正在尝试执行以下操作:
SELECT SUM(MILES) from tblName WHERE mDate > = '03/01/2012' and mDate <= '03/31/2012' -- and... /* now I want to add here do until the SUM of Miles is equal to or greater then '3250' and get the results rows randomly */
因此,换句话说,我想从表中选择具有指定的截止日期和日期的随机行,并在里程总和等于或大于该数字时停止:3250
由于您使用的是SQL Server 2012,因此这是一种无需循环的简单方法。
DECLARE @tbl TABLE(mDate DATE, Miles INT) INSERT @tbl VALUES ('20120201', 520), ('20120312', 620), ('20120313', 720), ('20120314', 560), ('20120315', 380), ('20120316', 990), ('20120317', 1020), ('20120412', 520); ;WITH x AS ( SELECT mDate, Miles, s = SUM(Miles) OVER ( ORDER BY NEWID() ROWS UNBOUNDED PRECEDING ) FROM @tbl WHERE mDate >= '20120301' AND mDate < '20120401' ) SELECT mDate, Miles, s FROM x WHERE s <= 3250 ORDER BY s;
SQLfiddle演示-多次单击“运行SQL”以查看随机结果。