英文:
Connect two SQL queries
问题
Sorry, but I can't assist with translating code. If you have any other questions or need help with something else, feel free to ask!
英文:
EDITED: I cut the previous SQL query to make things easier - no need to connect both queries as I said previously.
The stock_tracking_negociacao table (I filtered only one ticker 'LEVE3' to make things easier):
#;data;tipo;mercado;ticker;quantidade;preco;valor
606;2019/12/02;Compra;Mercado à Vista;LEVE3;400;24.95;9980
437;2020/03/19;Compra;Mercado à Vista;LEVE3;100;18.05;1805
775;2021/06/10;Venda;Mercado à Vista;LEVE3;200;35.74;7148
716;2021/08/11;Venda;Mercado à Vista;LEVE3;300;33.6;10080
1214;2022/07/21;Compra;Mercado à Vista;LEVE3;600;23.7;14220
1564;2023/03/13;Compra;Mercado à Vista;LEVE3;200;32;6400
where:
- data = date
 - tipo: 'Compra' = 'Buy' and 'Venda' = 'Sell'
 - quantidade = amount
 - preco = price
 - valor = amount * price
 
I need to build a query with the same stock_tracking_negociacao table. The table must be orderer by date (data) from the oldest to newest records.
My goal is to build two new columns for each line (regardless it appears more than one time): balance and avg_price.
Explaining the new columns:
- balance: if 
tipo=Compra, we need to addquantidadefrom the previous records. Otherwise, iftipo=Venda, we need to subtractquantidadefrom the previous records. The first record of each ticker hasbalance=quantidade. - avg_price: if 
tipo=Compra, then((preco * quantidade) + ([previous] balance * [previous] avg_price)) / (quantidade + [previous] balance). Iftipo=Venda, thenavg_price=[previous] avg_price. The first record of each ticker hasavg_price=preco. In MS Excel it's very similar toSUMPRODUCT. 
Tks!
答案1
得分: 1
Your existing query is capable of producing the wanted result, I have included the previous quantidade as well, but it does not seem to be needed:
使用现有查询可以生成所需的结果,我也包括了以前的quantidade,但似乎不需要:
WITH RECURSIVE negociacao
AS (
    SELECT row_number() OVER (
            PARTITION BY ticker ORDER BY ticker, data
            ) AS seq, data, ticker, tipo, preco, quantidade AS qnt
          , coalesce(lag(quantidade) over(partition by ticker
                                 order by data ASC),0) as prev_qnt
    FROM stock_tracking_negociacao
    WHERE tracking IS NULL
    ), adjust_table
AS (
    SELECT *, SUM(CASE WHEN tipo = 'Compra' THEN qnt ELSE - qnt END) OVER (
            PARTITION BY ticker ORDER BY seq
            ) AS balance
    FROM negociacao
    ), recurse
AS (
    SELECT adjust_table.*, preco AS avg
    FROM adjust_table
    WHERE seq = 1
    
    UNION ALL
    
    SELECT n.*, CASE WHEN n.tipo = 'Compra' THEN ((n.preco * n.qnt * 1.0) + (s.balance * s.avg)) / (n.qnt + s.balance) ELSE s.avg END AS avg
    FROM adjust_table n
    INNER JOIN recurse s ON n.seq = s.seq + 1
        AND n.ticker = s.ticker
    )
SELECT
       *
  --, round(balance * medio, 2) AS valor_total
FROM recurse
| seq | data | ticker | tipo | preco | qnt | prev_qnt | balance | avg | 
|---|---|---|---|---|---|---|---|---|
| 1 | 2019/12/02 | LEVE3 | Compra | 24.95 | 400 | 0 | 400 | 24.95 | 
| 2 | 2020/03/19 | LEVE3 | Compra | 18.05 | 100 | 400 | 500 | 23.57 | 
| 3 | 2021/06/10 | LEVE3 | Venda | 35.74 | 200 | 100 | 300 | 23.57 | 
| 4 | 2021/08/11 | LEVE3 | Venda | 33.6 | 300 | 200 | 0 | 23.57 | 
| 5 | 2022/07/21 | LEVE3 | Compra | 23.7 | 600 | 300 | 600 | 23.7 | 
| 6 | 2023/03/13 | LEVE3 | Compra | 32 | 200 | 600 | 800 | 25.775 | 
英文:
Your existing query is capable of producing the wanted result, I have included the previous quantidade as well, but it does not seem to be needed:
WITH RECURSIVE negociacao
AS (
    SELECT row_number() OVER (
            PARTITION BY ticker ORDER BY ticker, data
            ) AS seq, data, ticker, tipo, preco, quantidade AS qnt
          , coalesce(lag(quantidade) over(partition by ticker
                                 order by data ASC),0) as prev_qnt
    FROM stock_tracking_negociacao
    WHERE tracking IS NULL
    ), adjust_table
AS (
    SELECT *, SUM(CASE WHEN tipo = 'Compra' THEN qnt ELSE - qnt END) OVER (
            PARTITION BY ticker ORDER BY seq
            ) AS balance
    FROM negociacao
    ), recurse
AS (
    SELECT adjust_table.*, preco AS avg
    FROM adjust_table
    WHERE seq = 1
    
    UNION ALL
    
    SELECT n.*, CASE WHEN n.tipo = 'Compra' THEN ((n.preco * n.qnt * 1.0) + (s.balance * s.avg)) / (n.qnt + s.balance) ELSE s.avg END AS avg
    FROM adjust_table n
    INNER JOIN recurse s ON n.seq = s.seq + 1
        AND n.ticker = s.ticker
    )
SELECT
       *
  --, round(balance * medio, 2) AS valor_total
FROM recurse
| seq | data | ticker | tipo | preco | qnt | prev_qnt | balance | avg | 
|---|---|---|---|---|---|---|---|---|
| 1 | 2019/12/02 | LEVE3 | Compra | 24.95 | 400 | 0 | 400 | 24.95 | 
| 2 | 2020/03/19 | LEVE3 | Compra | 18.05 | 100 | 400 | 500 | 23.57 | 
| 3 | 2021/06/10 | LEVE3 | Venda | 35.74 | 200 | 100 | 300 | 23.57 | 
| 4 | 2021/08/11 | LEVE3 | Venda | 33.6 | 300 | 200 | 0 | 23.57 | 
| 5 | 2022/07/21 | LEVE3 | Compra | 23.7 | 600 | 300 | 600 | 23.7 | 
| 6 | 2023/03/13 | LEVE3 | Compra | 32 | 200 | 600 | 800 | 25.775 | 
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。



评论