在 SQL 中插入值的最佳方法
我有一个包含特定日期的速率的表:
Rates
Id | Date | Rate
----+---------------+-------
1 | 01/01/2011 | 4.5
2 | 01/04/2011 | 3.2
3 | 04/06/2011 | 2.4
4 | 30/06/2011 | 5
我想根据简单的线性插值获得输出速率。
因此,如果我输入 17/06/2011:
Date Rate
---------- -----
01/01/2011 4.5
01/04/2011 3.2
04/06/2011 2.4
17/06/2011
30/06/2011 5.0
线性插值是 (5 + 2,4) / 2 = 3,7
有没有办法做一个简单的查询(SQL Server 2005),或者这种事情需要以编程方式完成(C#...)?
I have a table with rate at certain date :
Rates
Id | Date | Rate
----+---------------+-------
1 | 01/01/2011 | 4.5
2 | 01/04/2011 | 3.2
3 | 04/06/2011 | 2.4
4 | 30/06/2011 | 5
I want to get the output rate base on a simple linear interpolation.
So if I enter 17/06/2011:
Date Rate
---------- -----
01/01/2011 4.5
01/04/2011 3.2
04/06/2011 2.4
17/06/2011
30/06/2011 5.0
the linear interpolation is (5 + 2,4) / 2 = 3,7
Is there a way to do a simple query (SQL Server 2005), or this kind of stuff need to be done in a programmatic way (C#...) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
像这样的东西(已更正):
Something like this (corrected):
正如@Mark 已经指出的那样,
CROSS JOIN
有其局限性。一旦目标值超出定义值的范围,就不会返回任何记录。而且上述解决方案仅限于一种结果。对于我的项目,我需要对整个 x 值列表进行插值,并提出了以下解决方案。也许其他读者也感兴趣?
运行上述脚本时,您将在表
#ddd
中获得以下数据网格点[[该表包含两个身份的网格点(
id=1
和id =2
)。在我的示例中,我通过在valstyp
CTE 中使用where id=1
仅引用了1
组。可以更改此值以满足您的要求。 ]]和结果表
#vals
,其中插值数据位于列yy
中:最后一列
itype
表示插值/外推的类型用于计算值:可以找到此工作示例此处< /a>.
As @Mark already pointed out, the
CROSS JOIN
has its limitations. As soon as the target value falls outside the range of defined values no records will be returned.Also the above solution is limited to one result only. For my project I needed an interpolation for a whole list of x values and came up with the following solution. Maybe it is of interested to other readers too?
When running the above script you will get the following data grid points in table
#ddd
[[ The table contains grid points for two identities (
id=1
andid=2
). In my example I referenced only the1
-group by usingwhere id=1
in thevalstyp
CTE. This can be changed to suit your requirements. ]]and the results table
#vals
with the interpolated data in columnyy
:The last column
itype
indicates the type of interpolation/extrapolation that was used to calculate the value:This working example can be found here.
这里 CROSS JOIN 的技巧是,如果任一表没有行 (1 * 0 = 0),则它不会返回任何记录,并且查询可能会中断。更好的方法是使用带有不等式条件的 FULL OUTER JOIN (以避免获得多于一行)
The trick with CROSS JOIN here is it wont return any records if either of the table does not have rows (1 * 0 = 0) and the query may break. Better way to do is use FULL OUTER JOIN with inequality condition (to avoid getting more than one row)