在SQL Server中取计算的中位数
SQL Server 中的 MyTable 包含 _TimeStamp、Column1、Column2 和 Column3,它们具有以下值:
_TimeStamp Column1 Column2 Column3
'2010-10-11 15:55:25.40' 10 3 0.5
'2010-10-11 15:55:25.50' 20 9 0.7
'2010-10-11 15:55:25.60' 15 2 1.3
'2010-10-11 15:55:25.70' 17 8 2.7
'2010-10-11 15:55:25.80' 42 6 3.6
'2010-10-11 15:55:25.90' 14 2 0.4
我想找到 中值 4*Column1*Column2*Column3 的值。每行的产品是:
60
504
156
1468.8
3628.8
44.8
由于条目数为偶数,因此中值是两个“中间”条目(156 和 504)的平均值,即 330。另外,我只想对选定时间范围内的值执行中值,并且该解决方案无法更改不属于我的数据库。我编辑了类似查询 获取如下所示的查询,但由于列名无效而失败。有什么建议吗?
SELECT
AVG(4*Column1*Column2*Column3)
FROM
(
SELECT
4*Column1*Column2*Column3,
ROW_NUMBER() OVER (
ORDER BY 4*Column1*Column2*Column3 ASC, _TimeStamp ASC) AS RowAsc,
ROW_NUMBER() OVER (
ORDER BY 4*Column1*Column2*Column3 DESC, _TimeStamp DESC) AS RowDesc
FROM MyTable WHERE
_TimeStamp BETWEEN '2010-10-11 15:55:25.40' AND '2010-10-11 15:55:25.90'
) x
WHERE
RowAsc IN (RowDesc, RowDesc - 1, RowDesc + 1)
MyTable in SQL Server contains _TimeStamp, Column1, Column2, and Column3, which have the following values:
_TimeStamp Column1 Column2 Column3
'2010-10-11 15:55:25.40' 10 3 0.5
'2010-10-11 15:55:25.50' 20 9 0.7
'2010-10-11 15:55:25.60' 15 2 1.3
'2010-10-11 15:55:25.70' 17 8 2.7
'2010-10-11 15:55:25.80' 42 6 3.6
'2010-10-11 15:55:25.90' 14 2 0.4
I would like to find the median value of 4*Column1*Column2*Column3. The products for each row are:
60
504
156
1468.8
3628.8
44.8
Since there are an even number of entries, the median value is the average of the two 'middle' entries (156 and 504), or 330. Also I only want to perform the median on values that fall within a chosen time range, and the solution can't alter the database which isn't mine. I edited a similar query to get the query shown below, but it fails because a column name is invalid. Any suggestions?
SELECT
AVG(4*Column1*Column2*Column3)
FROM
(
SELECT
4*Column1*Column2*Column3,
ROW_NUMBER() OVER (
ORDER BY 4*Column1*Column2*Column3 ASC, _TimeStamp ASC) AS RowAsc,
ROW_NUMBER() OVER (
ORDER BY 4*Column1*Column2*Column3 DESC, _TimeStamp DESC) AS RowDesc
FROM MyTable WHERE
_TimeStamp BETWEEN '2010-10-11 15:55:25.40' AND '2010-10-11 15:55:25.90'
) x
WHERE
RowAsc IN (RowDesc, RowDesc - 1, RowDesc + 1)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您需要对候选语句做的就是在子查询中为计算值添加别名,然后在外部查询中请求该别名的 AVG:
我还没有不过还没有测试过。
I think all you need to do to your candidate statement is to alias the computed value in the subquery, then ask for the
AVG
of that alias in the outer query:I haven't tested this though.