开发者社区> 问答> 正文

从一个表中选择给定年份中所有月份的记录,从第二个表中选择记录

我的数据库中有两个表:

MembershipInstallments (ProjectId,AllotmentId,InstallmentId,EntryDate,AmountPaid) Memberships (ProjectId,AllotmentId,ClientId,ClientName,RegistrationNo) 我想选择客户在一年内按月付款的方式。还有那年开始之前支付的金额。我想要的结果集是

假设在2019年:

ClientName, RegistrationNumbers, PreviouslyPaidAmount (i.e. all amounts paid in 2018), AmountPaidInJuly 2019, AmountPaidInAugust2019. ..... AmountPaidIn Jun2020 其中一个月是EntryDate从MembershipInstallments表。

我像这样尝试过,但是对于大型数据集,它花费的时间太长:

SELECT ClientName, RegistrationNo, (SELECT ISNULL(SUM(AmountPaid),0) FROM MembershipInstallments WHERE ProjectId = Membership.ProjectId AND AllotmentId = Membership.AllotmentId AND EntryDate < @fromDate) ASPreviouslyPaid, (SELECT ISNULL(SUM(AmountPaid), 0) FROM MembershipInstallments WHERE ProjectId = Membership.ProjectId AND AllotmentId = Memberhsip.AllotmentId AND (MONTH(EntryDate) = 7) AND (YEAR(EntryDate) = YEAR(@fromDate)) AS JulyPayment FROM Memberships WHERE ProjectId = @projectId 任何帮助将不胜感激。

问题来源于stack overflow

展开
收起
保持可爱mmm 2019-11-18 11:44:09 436 0
1 条回答
写回答
取消 提交回答
  • 标量子查询往往无法优化。在您的情况下(相同的加入条件),您可以简单地利用条件聚合:

    SELECT ms.ClientName,ms.RegistrationNo, Sum(CASE WHEN mi.EntryDate<@fromDate THEN mi.AmountPaid ELSE 0 end) AS PreviouslyPaid, Sum(CASE WHEN (Month(mi.EntryDate) = 7) AND (Year(mi.EntryDate) = Year(@fromDate)) THEN mi.AmountPaid ELSE 0) FROM Memberships AS ms LEFT JOIN MembershipInstallments AS mi -- don't know if Outer join is really needed ON mi.ProjectId=ms.ProjectId AND mi.AllotmentId=ms.AllotmentId WHERE ms.ProjectId=@projectId 您可能能够在加入之前进行聚合,即在CTE中进行聚合以进一步提高性能:

    WITH cte AS ( SELECT
    ProjectId, AllotmentId, Sum(CASE WHEN EntryDate<@fromDate THEN AmountPaid ELSE 0 END) AS PreviouslyPaid, Sum(CASE WHEN (Month(EntryDate) = 7) AND (Year(EntryDate) = Year(@fromDate)) THEN AmountPaid ELSE 0 END) AS JulyPayment FROM MembershipInstallments WHERE ProjectId=@projectId GROUP BY ProjectId, AllotmentId ) SELECT ms.ClientName, ms.RegistrationNo, cte.PreviouslyPaid, cte.JulyPayment FROM Memberships AS ms JOIN cte ON cte.ProjectId=ms.ProjectId AND cte.AllotmentId=ms.AllotmentId WHERE ms.ProjectId=@projectId 在这两种情况下,都要仔细检查结果是否正确(取决于这些表之间的实际关系)

    2019-11-18 11:44:19
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载