0

我这里有这个 SQL 代码,我的愿望是计算每个学生每次存款的最新费用余额。到目前为止,我已经能够做到这一点,但现在的问题是我如何只选择最新的余额,而忽略其他以前的条目/余额

(select

     f.Totals -SUM(Total) OVER(ORDER BY pay_Id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as Balance,
     p.Total as 'TotalPaid',
c.class_id as 'ClassID',
p.std_ID as 'STDID',
c.class_name as 'Class',
a.ad_stdname as 'Name',
t.term_id as 'TermID',
t.term_name as 'Term',
p.Date as 'Date',
case when (st.str_id = null) then '-' else st.str_id end as 'StrID',
case when (p.Tution_fee = null) then '0' else p.Tution_fee end as 'Tution',
case when (p.adm_fee = null) then '0' else p.adm_fee end as 'Admission',
case when (p.Activity_fee = null) then '0' else p.Activity_fee end as 'Activity',
case when (p.Textbk_Statio = null) then '0' else p.Textbk_Statio end as 'Texbooks',
case when (p.Transport_fee = null) then '0' else p.Transport_fee end as 'Transport'
from Payments p
 inner join Admissions a 
 on a.ad_id = p.std_ID
 inner join classes c 
 on c.class_id =p.class_id
   inner join fees f on f.fee_classID = p.class_id and f.Term_id = p.Term_id
 left join streams st
 on st.str_id = p.str_id
 inner join terms t 
 on p.Term_id = t.term_id
 where a.ad_id = 29
 )
 order by  p.std_name,Balance,p.Date  desc

这是我当前的输出

在此处输入图像描述

4

1 回答 1

0

我在下面的示例中为每个用户选择了最小值:

用户日期值

Sonu 1/2/2010 1.5
Monu 1/3/2010 2.5
Arun 8/4/2009 3.5
Sonu 2/2/2010 1.0
Monu 12/2/2009 0.5

select t.username, t.date, t.value
from MyTable t
inner join (
    select username, min(value) as value
    from MyTable
    group by username
) tm on t.username = tm.username and t.value = tm.value

演示 sql 小提琴

使用上述逻辑在您的代码中实现

我试图在您的查询中适应上述逻辑。现在我刚刚使用 stdid 进行分组,您可以相应地添加更多。你可能会得到一些语法错误:

with MyTable as (select   
f.Totals -SUM(Total) OVER(ORDER BY pay_Id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as Balance,
p.Total as 'TotalPaid',
c.class_id as 'ClassID',
p.std_ID as 'STDID',
c.class_name as 'Class',
a.ad_stdname as 'Name',
t.term_id as 'TermID',
t.term_name as 'Term',
p.Date as 'Date',
case when (st.str_id = null) then '-' else st.str_id end as 'StrID',
case when (p.Tution_fee = null) then '0' else p.Tution_fee end as 'Tution',
case when (p.adm_fee = null) then '0' else p.adm_fee end as 'Admission',
case when (p.Activity_fee = null) then '0' else p.Activity_fee end as 'Activity',
case when (p.Textbk_Statio = null) then '0' else p.Textbk_Statio end as 'Texbooks',
case when (p.Transport_fee = null) then '0' else p.Transport_fee end as 'Transport'
from Payments p
 inner join Admissions a 
 on a.ad_id = p.std_ID
 inner join classes c 
 on c.class_id =p.class_id
 inner join fees f on f.fee_classID = p.class_id and f.Term_id = p.Term_id
 left join streams st
 on st.str_id = p.str_id
 inner join terms t 
 on p.Term_id = t.term_id
 where a.ad_id = 29
 order by  p.std_name,Balance,p.Date  desc) select * from MyTable 
 inner join
 (
    select STDID, min(Balance) as value
    from MyTable
    group by STDID
) tm on t.STDID = tm.STDID and t.Balance = tm.Balance
于 2020-06-20T14:53:33.107 回答