根据另一列获取最新值,并独立求和另一列

时间:2019-07-02 20:53:07

标签: sql sql-server

情况:

我有一个表,其中包含付费和免费交易,余额表将免费和付费交易合并在一起。

目标:

我需要获取已支付的交易总额和最近的余额

结构:

+-----------+---------+--------+-------------+------------+
| member_id | balance | amount |    type     | issue_date |
+-----------+---------+--------+-------------+------------+
| varchar   | int     | int    | pay or free | datetime   |
+-----------+---------+--------+-------------+------------+

当前查询:

        select t1.member_id, t2.balance, sum(t1.amount) as total
        from table AS t1
        inner join (select member_id, 
                            balance, 
                            ROW_NUMBER() over (partition by member_id order by issue_date desc) AS ranks 
                    from table
                    ) AS t2 on t1.member_id=t2.member_id and t2.ranks = 1
        where [type] = 'pay'
        group by t1.member_id, t2.balance

这似乎可行,但对于没有索引issue_date的数百万行的表而言,效率极低。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

一种方法使用窗口函数和select distinct

select distinct t.member_id,
       first_value(case when t.type = 'pay' then t.balance end) over (partition by t.member_id order by (case when t.type = 'pay' then 1 else 2 end), t.issue_date desc), 
       sum(t.amount) over (partition by t.member_id) as total
from table t;

不幸的是,SQL没有first_value()聚合函数。