【问题标题】:How to achieve in MySql what "retain" does in SAS?如何在 MySql 中实现 SAS 中的“保留”?
【发布时间】:2015-09-29 09:53:50
【问题描述】:

我想将变量的值从第 1 行转移到第 2 行,将其用于第 2 行的计算,然后将输出带到查询中的第 3 行。该过程重复 1000 行。 Retain 在 SAS 中做到这一点,我在 MySql 中如何做到这一点?

【问题讨论】:

    标签: mysql sas retain


    【解决方案1】:

    在 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
    

    【讨论】:

    • 谢谢!但是,我尝试了类似的方法并收到错误“子查询返回超过 1 行”
    • SELECT T1.UID, T1.discount_bucket, T1.discount_id, T1.subcatid, T1.brandid, T1.num_cb_requests, T1.recom_pog, T1.App, T1.Remain, (选择 (CASE WHEN (T2.recom_pog>T2.num_cb_requests) THEN (T2.recom_pog-T2.num_cb_requests+T1.Remain) END) 来自 analytics_fashion.final_table_kb T2 其中 T1.subcatid = T2.subcatid 和 T1.brandid = T2.brandid 和 T1.UID >= (T2.UID) ) AS Remain2 FROM analytics_fashion.final_table_kb T1
    • 您没有在子查询中使用聚合函数:Count()Sum()Avg()Max()Min()。尝试将 Case 语句包装在 Sum() 中。
    【解决方案2】:

    在 MySQL 中,您可以使用变量来执行此操作。下面是一个计算行数的例子:

    select t.*, (@rn := @rn + 1) as rn
    from table t cross join
         (select @rn := 0) params
    order by col;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多