【问题标题】:Is there an analytical function in mysql to solve this issue?mysql中有解析函数来解决这个问题吗?
【发布时间】:2012-10-24 00:21:05
【问题描述】:

我有一个如下的mysql表

id   trader price
111   abc    5
222   xyz    5.20
333   abc    5.70
444   xyz    5
555   abc    5.20

我想要一个结果来找出每个交易者增加或减少价格的次数 如下

id   trader price  lagged_price   flag
111   abc    5
222   xyz    5.20   5        
333   abc    5.70   5.20        increased 
444   xyz    5      5.70        increased  
555   abc    5.20   5           reduced
                    5.20        increased

lagged_price 是滞后于原始列价格的列。我需要有一个标志,表明交易者在特定时间增加或减少了价格 在上述情况下,最终结果是

trader abc 两次涨价 交易员xyz涨价降价

【问题讨论】:

标签: mysql


【解决方案1】:

我看到你在帖子中提出了不同的问题:Compare rows in same table in mysql

尽管如此,以下是上述问题的解决方案:(假设您的表称为“tab”,并且 ID 实际上减少了,因此“lag”表示“之前”,就像在您的示例数据中一样)

SELECT a.id, a.trader, a.price, b.price as lagged_price
     , case when a.price > b.price then 'increased'
            when a.price < b.price then 'decreased'
            else 'same'
       end as flag
  FROM tab a
  JOIN tab b 
    ON a.trader = b.trader AND a.id > b.id
  LEFT OUTER JOIN tab c 
    ON a.trader = c.trader AND a.id > c.id AND b.id < c.id
 WHERE c.id IS NULL

您可以在我对您的其他问题的回答中查看为什么这样做的详细信息。

希望这会有所帮助!

约翰...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    • 2011-07-16
    • 1970-01-01
    • 2011-07-04
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多