【问题标题】:How to search within date range for multi entities?如何在日期范围内搜索多个实体?
【发布时间】:2019-06-20 08:32:21
【问题描述】:

我有以下表格:

  • 公司历史: Id StartDate EndDate
  • CustomerHistory Id CompanyId StartDate EndDate
  • CustomerPayment Id CustomerId StartDate EndDate 金额

我想制作一份报告,以搜索特定日期范围(firstDay、endDay)内的所有付款及其客户和公司。

我仅使用此代码为 CustomerPayment 执行此操作,并且我必须对 CustomerHistory 和 companyHistory 表执行相同操作。

而且性能真的很差。

有什么方法可以改进查询或者我应该改变我的数据库设计吗?

var payments= db.CustomerPayment.Where(s =>> 
             ((firstDay <= s.EndDate && lastDay >= s.StartDate) && 
              (lastDay <= s.EndDate || lastDay >= s.EndDate) && 
              (firstDay > s.StartDate || firstDay < s.StartDate)) ||
             ((s.EndDate == null) && ((firstDay >= s.StartDate) || 
              (firstDay <= s.StartDate && lastDay >= s.StartDate)));

【问题讨论】:

标签: c# sql linq


【解决方案1】:
  1. 您说您希望每次付款(付款总是在准确的时刻完成),所以我很困惑为什么会有结束日期和开始日期。如果可能,请失去其中之一。
  2. 如果开始日期早于报告的最后一天并且您的结束日期超过报告的开始日期,则付款在您的窗口内。显然,endDate 可以有一个空值,意思是无限的,所以我在下面干净、简单的语句中添加了这一点:

var payments= db.CustomerPayment.Where(s =>> (s.StartDate <= lastDay && (a.EndDate >= firstDay || a.EndDate == null));

  1. 如果此查询的性能仍然欠佳,您的数据库中的记录太多,无法提高性能。您可以按照@Uwe Keim 的建议编写索引,也可以每月(或每周或任何最小的报告指标)计算一次每位客户的付款金额,并将这些结果存储在您的数据库中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    • 2021-08-28
    • 2017-10-25
    • 2012-02-26
    • 1970-01-01
    相关资源
    最近更新 更多