0

我有两张桌子。

表1->付款

AdmissionNum(PK)  |  StudName |   Fees |

       1               sagar      5000 
       2               nilesh     6000
       3               amar       4000  

表2->支付详情

AdmissionNum(FK) | RemainingFees |   Date       |  Payment
        1             4000          1/1/2012          1000
        2             5000          2/5/2012          1000
        1             3500          2/10/2012         1500
        1             2500          2/15/2012         1000
        2             2500          2/20/2012         2500
        3             0             3/25/2012         4000

我尝试了不同的查询,但无法在支付表和 paymentDetails 表之间建立联合。我正在制作 C# windows 应用程序。当特定学生支付费用时,他的记录存储在 paymentDetails 表中。我只想提取未结费用的详细信息,即剩余费用大于 0 但 paymentDetais 表中的最后一个详细信息的学生,即。

我的预期结果表是-

AdmissionNum  |  StudName |   Fees | RemainingFees

       1           sagar      5000    2500
       2           nilesh     6000    2500
4

4 回答 4

2

试试这个:

with cte as (select P.AdmissionNum , P.StudName,   P.Fees , D.RemainingFees,row_number() 
over ( partition by  P.AdmissionNum order by [DATE] desc) as rn
from Payment P
join PaymentDetails D
on P.AdmissionNum=D.AdmissionNum
where RemainingFees>0)
select AdmissionNum ,StudName,  Fees , RemainingFees
from cte
where rn=1


SQL小提琴演示

于 2012-10-21T04:40:36.107 回答
0

我会这样做如下。

SELECT 
       P.AdmissionNum,
       P.StudName,
       P.Fees
       P.Fees - PD.Payment 'RemainingFees'
FROM
    Payment P
    JOIN (SELECT 
                AdmissionNum, 
                SUM(Payment) 'Payment' 
          FROM 
                PaymentDetails 
          GROUP BY AdmissionNum
    ) AS PD
    ON P.AdmissionNum = PD.AdmissionNum
WHERE 
    P.Fees - PD.Payment > 0
于 2012-10-21T04:25:12.290 回答
0

试试下面:

   SELECT a.AdmissionNum, a.StudName , a.Fees, b.remFees as RemainingFees
   FROM Payment a, 
        (SELECT AdmissionNum, min(RemainingFees) as remFees 
           FROM PaymentDetails b GROUP BY AdmissionNum) b
   WHERE a.AdmissionNum = b.AdmissionNum 
        and b.remFees >0;
于 2012-10-21T04:28:23.457 回答
0

试试下面的查询:

Select a.AdmissionNum, a.StudName, a.Fees, b.RemainingFees 
from Payment a 
inner join paymentDetails b on a.AdmissionNum = b.AdmissionNum
inner join (
   select AdmissionNum, max(date) as date 
   from paymentDetails 
   group by AdmissionNum
) c on a.AdmissionNum = c.AdmissionNum
where b.RemainingFees > 0 and b.Date = c.Date
于 2012-10-21T04:33:32.647 回答