【发布时间】:2020-05-20 11:11:51
【问题描述】:
我想将每个客户的所有消费金额相加,然后将结果除以客户在数据库中首次注册的日期;划分的结果将决定最赚钱和最不赚钱的客户。
Customer 表如下所示:
public class Customer
{
public int Id { get; set; }
public string Name{ get; set; }
public string Surname{ get; set; }
public int DayOB{ get; set; }
public int MonthOB{ get; set; }
public int YearOB{ get; set; }
public string Genre{ get; set; }
public string Email { get; set; }
public string Cellular{ get; set; }
public bool Privacy { get; set; }
public bool Profilation{ get; set; }
public bool Marketing { get; set; }
public decimal Points{ get; set; }
public decimal ConversionRate{ get; set; }
public DateTime RegisterDate{ get; set; }
public string QRCode { get; set; }
}
而事务表像:
public class Transaction
{
public int Id { get; set; }
public decimal SpentAmount{ get; set; }
public decimal AddedCoupon{ get; set; }
public decimal DeductCoupon{ get; set; }
public DateTime TransactionDate{ get; set; }
//FOREIGN KEY
public int CustomerId { get; set; }
//NAVIGATION
public Customer Customer { get; set; }
}
目前我已经尝试过这个 LINQ 查询
public async Task<IHttpActionResult> GetTransactions()
{
/*DateTime regDate= from c in db.Customers
select c.RegisterDate.Date;*/
DateTime currentDay= DateTime.UtcNow;
var query = from c in db.Customers
join t in db.Transactions on c.Id equals t.CustomerId
where t.Id != null
group t by t.CustomerId into ris
select new
{
CustomerId = ris.Key,
RegisterDate= ris.Select(c => c.Customer.RegisterDate.Date.Subtract(currentDay)),
Sum = ris.Sum(t => t.SpentAmount)
};
return Ok(query.OrderByDescending(ris => ris.Sum));
}
结果如下:
[
{
"CustomerId": 6,
"RegisterDate": [
"2020-03-01T00:00:00",
"2020-03-01T00:00:00"
],
"Sum": 46.00
},
{
"CustomerId": 7,
"RegisterDate": [
"2019-11-01T00:00:00",
"2019-11-01T00:00:00"
],
"Sum": 45.50
},
{
"CustomerId": 5,
"RegisterDate": [
"2020-02-01T00:00:00",
"2020-02-01T00:00:00"
],
"Sum": 31.00
}
]
CustomerId 的分组部分和 Sum 是正确的结果,但是当我尝试在当天和注册日之间进行差异的部分时,然后将其除以花费的金额,这给了我错误。
【问题讨论】:
-
您的输出与您显示的代码不匹配。
-
@NetMage 你是什么意思?我又试了一次,结果是这样的。。我唯一改变的是Select语句中的RegisterDay到RegisterDate
-
它给了我错误 -- 哪个?
-
@GertArnold 它说 LINQ 不接受 DateTime 及其任何方法。肯定那部分不好,但我已经厌倦了看看会发生什么。
-
您问题中发布的
select既不是RegisterDay也不是RegisterDate,而是PassedDay。你发错代码了吗?
标签: .net entity-framework linq