【发布时间】:2015-09-29 09:53:50
【问题描述】:
我想将变量的值从第 1 行转移到第 2 行,将其用于第 2 行的计算,然后将输出带到查询中的第 3 行。该过程重复 1000 行。 Retain 在 SAS 中做到这一点,我在 MySql 中如何做到这一点?
【问题讨论】:
我想将变量的值从第 1 行转移到第 2 行,将其用于第 2 行的计算,然后将输出带到查询中的第 3 行。该过程重复 1000 行。 Retain 在 SAS 中做到这一点,我在 MySql 中如何做到这一点?
【问题讨论】:
在 SQL 中,您可以使用子查询进行中间观察计算,并在嵌套查询和主查询之间关联值。由于 SAS 中 RETAIN 语句的典型用法涉及运行总计、计算值出现的次数、在 BY 组中设置指标,因此嵌套子查询可以复制这些功能。
以下示例演示跨分组观察运行聚合。
示例表
id group name amount
1 Object-oriented Java 100
2 Object-oriented C# 50
3 Object-oriented Python 75
4 Object-oriented PHP 65
5 Special Purpose SQL 80
6 Special Purpose XSLT 60
7 Statistical R 85
8 Statistical SAS 100
使用两个子查询查询运行计数和运行总和:
SELECT t1.id, t1.group, t1.name, t1.amount,
(SELECT Count(*) FROM maintable As t2
WHERE t1.group = t2.group AND t1.id >= t2.id) As RunningCount,
(SELECT Sum(t3.amount) FROM maintable As t3
WHERE t1.group = t3.group AND t1.id >= t3.id) As RunningAmount
FROM maintable As t1
输出
id group name amount RunningCount RunningAmount
1 Object-oriented Java 100 1 100
2 Object-oriented C# 50 2 150
3 Object-oriented Python 75 3 225
4 Object-oriented PHP 65 4 290
5 Special Purpose SQL 80 1 80
6 Special Purpose XSLT 60 2 140
7 Statistical R 85 1 85
8 Statistical SAS 100 2 185
【讨论】:
Count()、Sum()、Avg()、Max()、Min()。尝试将 Case 语句包装在 Sum() 中。
在 MySQL 中,您可以使用变量来执行此操作。下面是一个计算行数的例子:
select t.*, (@rn := @rn + 1) as rn
from table t cross join
(select @rn := 0) params
order by col;
【讨论】: