需要有关MySQL查询的帮助,我需要按stock_id按日期组获取起始余额和最终余额

时间:2018-06-18 04:39:14

标签: mysql

我需要从最早的日期到月末的结束余额和stock_id的组合获得起始余额。 我的表:

id    stock_id   balance     transact_at
1     1          100         2018-06-15
2     1          70          2018-06-16
3     1          30          2018-06-31
4     2          50          2018-06-01
5     2          10          2018-03-31

我想要输出:

stock_id start_balance    ending_balance
1        100              30   
2        50               10

3 个答案:

答案 0 :(得分:1)

MySQL中的一种方法是按stock_id聚合一次,找到开始和结束日期。然后,自行加入两次以获取在开始和结束日期发生的实际余额。

SELECT
    t1.stock_id,
    t2.balance AS start_balance,
    t3.balance AS ending_balance
FROM
(
    SELECT
        stock_id,
        MIN(transact_at) AS min_transact_at,
        MAX(transact_at) AS max_transact_at
    FROM my_table
    GROUP BY stock_id
) t1
INNER JOIN my_table t2
    ON t1.stock_id = t2.stock_id AND t2.transact_at = t1.min_transact_at
INNER JOIN my_table t3
    ON t1.stock_id = t3.stock_id AND t3.transact_at = t1.max_transact_at;

enter image description here

Demo

注意:为了后人的缘故,当MySQL 8+成为常态时,我们可以在这里使用ROW_NUMBER之类的东西,这样可以更容易地获得我们想要的结果。

答案 1 :(得分:1)

试试这个。在这一个中,两个内部查询通过获取对应于stock_id的最小和最大transact_at来获取起始余额和期末余额,然后父查询梳理两个查询以在单行中获得开始和结束余额。我也在下面分享了小提琴链接尝试。

select 
  tabledata1.stock_id, 
  startBalance,
  closingBalance 
  from (
      select 
      table1.stock_id,
      balance as startBalance 
      from table1 join 
      (
          select stock_id,
          min(transact_at) as transact_at 
          from Table1 group by stock_id
      ) startTransaction 
      on Table1.stock_id = startTransaction.stock_id and 
      Table1.transact_at = startTransaction.transact_at
  ) tabledata1
  join (
    select 
    table1.stock_id,
    balance as closingBalance 
    from table1 join 
    (
      select stock_id,
      max(transact_at) as transact_at
      from Table1 group by stock_id
    ) endTransaction 
    on Table1.stock_id = endTransaction.stock_id 
    and Table1.transact_at = endTransaction.transact_at
  ) tabledata2 
  on tabledata1.stock_id = tabledata2.stock_id;

Demo

答案 2 :(得分:0)

试一试。

SELECT stock_id,MAX(balance) as start_balance, MIN(balance) as ending_balance  FROM tbl_balance GROUP BY stock_id