SQL Server查询-使SUM最大化的间隔值

时间:2018-12-11 12:34:00

标签: sql sql-server count max

我需要一个SQL Server查询,该查询返回对应于一个十进制字段的两个值(t1和t2),以便它们定义一个使SUM最大化的间隔。对成功的记录(字段结果> 0)和不成功的记录(字段结果<0)执行SUM。换句话说:在哪个价值细分中优化了净结果? 有任何想法吗?预先感谢!

更多信息

-table“ operations”是目标SQL表,这些查询将涉及相关字段: SELECT t from operations where result > 0

SELECT COUNT(*) AS num from operations where result > 0

-字段“ t”是一个十进制值,我正在搜索“ t”的2个值,例如“ t1 = 1.25”和“ t2 = 2.6”

-字段“结果”是一个整数值,可以是> 0(例如,赢得胜利,例如“ 15”)或<0(例如,失去胜利,例如“ -10”)

-以下查询可以正常返回“ t”(t1和t2)的间隔,该间隔被任意确定为t> 1和t <1.5: SELECT DISTINCT (select MIN(t) from operations where t > 1) As t1, (select MAX(t) from operations where t < 1.5) As t2 from operations 目的: -table“ operations”大约有500条记录,其中一些记录是成功的(“ result”> 0)或不成功的(“ result” <0),“ t”是一个具有多个值的十进制字段,可以说介于1.2和5.8之间 -为简化起见,假设我们只有两个字段“ t”和“结果”-t的2个值是什么(t1和t2),因此对于t> t1和t

+------------+-------------+
| t          | result      |
+------------+-------------+
| 1.25       |          15 |
| 1.1        |         -12 |
| 3.8        |          10 |
+------------+-------------+

对于这个小的记录集,t的期望值将为t1 = 1.25和t2 = 3.8,因为在1.25 <= t <= 3.8的间隔内,结果将最大化(总结果= 15 + 10 = 25)。例如1.1 <= t <= 1.25将导致总结果= 15-12 = 3,这不是最佳选择。

1 个答案:

答案 0 :(得分:0)

如果您将结果排在前2位,并包含ROW_NUMBER。
然后根据row_number可以知道t1和t2。

var a = (function(){
  var x = 0;
  var y = function(){
	x++;
	console.log(x);
  }
  var z = function(){
	return x;
  }
  return {
	x, y, z
  }
})();

console.log(a.x);
a.y();
a.y();
console.log(a.x);
console.log(a.z());

结果:

SELECT 
MAX(case when rn = 1 then t end) as t1, 
MAX(case when rn = 2 then t end) as t2, 
MAX(case when rn = 1 then result end) as result1, 
MAX(case when rn = 2 then result end) as result2,
SUM(result) as optimum
FROM
(
  SELECT result, t, ROW_NUMBER() OVER (ORDER BY t) as rn
  FROM
  (
    SELECT TOP 2 result, t
    FROM operations
    WHERE t BETWEEN 1.00 AND 4.00
    ORDER BY result DESC
  ) q1
) q2;