MySQL show sum of difference of two values

后端 未结 3 1793
星月不相逢
星月不相逢 2021-01-25 02:43

Below is my query.

SELECT n.`name`,n.`customer_id`,m.`msn`, m.kwh,
   m.kwh - LAG(m.kwh) OVER(PARTITION BY n.`customer_id` ORDER BY m.`data_date_time`) AS kwh_dif         


        
相关标签:
3条回答
  • 2021-01-25 03:11

    MAke an outer Query

    SELECT
    `name`,`customer_id`,`msn`, SUM(kwh_diff) kwh_diff
    FROM
    (
        SELECT n.`name`,n.`customer_id`,m.`msn`, m.kwh,
           m.kwh - LAG(m.kwh) OVER(PARTITION BY n.`customer_id` ORDER BY m.`data_date_time`) AS kwh_diff
        FROM mdc_node n
        INNER JOIN `mdc_meters_data` m ON n.`customer_id` = m.`cust_id`
        WHERE n.`lft` = 5 AND n.`icon` NOT IN ('folder')
        AND m.`data_date_time` BETWEEN NOW() - INTERVAL 30 DAY AND NOW() ) t1
    GROUP BY `name`,`customer_id`,`msn`
    
    0 讨论(0)
  • 2021-01-25 03:22

    You want to sum the differences between consecutive rows.
    Say, for example, that you have these values for the column kwh:

    kwh
    ---
    10
    12
    14
    17
    25
    32
    

    so the differences are:

    kwh_diff
    --------
    0
    12-10
    14-12
    17-14
    25-17
    32-25
    

    The sum of these differences is equal to 32-10 which is:

    the diffference between the last value and the first value

    So what you need is window function FIRST_VALUE() to obtain these values:

    SELECT DISTINCT n.`name`, n.`customer_id`, m.`msn`, 
       FIRST_VALUE(m.kwh) OVER (PARTITION BY n.`customer_id` ORDER BY m.`data_date_time` DESC) -
       FIRST_VALUE(m.kwh) OVER (PARTITION BY n.`customer_id` ORDER BY m.`data_date_time` ASC) AS kwh_diff
    FROM mdc_node n
    INNER JOIN `mdc_meters_data` m ON n.`customer_id` = m.`cust_id`
    WHERE n.`lft` = 5 AND n.`icon` NOT IN ('folder')
    AND m.`data_date_time` BETWEEN NOW() - INTERVAL 30 DAY AND NOW()
    

    and no subquery or aggregation is needed.

    I kept in my code PARTITION BY n.customer_id because you use it in your code, although you may need PARTITION BY n.customer_id, m.msn.

    0 讨论(0)
  • 2021-01-25 03:28

    You can’t use window functions within an aggregate function (while the opposite is possible), Here, you need to use a subquery, and aggregate in the outer query:

    SELECT name, customer_id, SUM(kwh_diff) sum_kwh_diff
    FROM (
        SELECT n.`name`,n.`customer_id`,m.`msn`, m.kwh,
           m.kwh - LAG(m.kwh) OVER(PARTITION BY n.`customer_id` ORDER BY m.`data_date_time`) AS kwh_diff
        FROM mdc_node n
        INNER JOIN `mdc_meters_data` m ON n.`customer_id` = m.`cust_id`
        WHERE n.`lft` = 5 AND n.`icon` NOT IN ('folder')
        AND m.`data_date_time` BETWEEN NOW() - INTERVAL 30 DAY AND NOW()
    ) t
    GROUP BY name, customer_id
    
    0 讨论(0)
提交回复
热议问题