我会假设你MonthAmounts
表的结构是,像这样:
public class MonthlyAmount
{
public DateTime MonthYear { get; set;}
public string DebtType { get; set;}
public decimal DebtAmount { get; set;}
}
如果不是从你的问题清楚是否有将只有一个一个给定的债务类型的记录&月/年组合与否。而且由于您明确表示MonthYear
是DateTime
类型,我将假设每个月可能有特定债务类型的任何数量的记录。这种想法适合您需要组合在一起的单个交易表。如果我错了,请你澄清一下。
因此,这里需要查询:
var codedMonthlyAmounts =
from ma in MonthlyAmounts
let MonthCode =
ma.MonthYear.Year * 12
+ ma.MonthYear.Month
- 1
select new
{
MonthCode,
ma.DebtType,
ma.DebtAmount,
};
var latest =
from cma in codedMonthlyAmounts
group cma by cma.DebtType into gcmas
let DebtType = gcmas.Key
let current = gcmas
.GroupBy(gcma => gcma.MonthCode)
.OrderBy(ggcma => ggcma.Key)
.Last()
let DebtAmount = current.Sum(c => c.DebtAmount)
let monthCode = current.Key
let year = monthCode/12
let month = monthCode % 12 + 1
let MonthYear = new DateTime(year, month, 1)
select new MonthlyAmount()
{
DebtType = DebtType,
MonthYear = MonthYear,
DebtAmount = DebtAmount,
};
如果你想测试,如果这个工程,使用此代码:
var MonthlyAmounts = new List<MonthlyAmount>();
var now = DateTime.Now;
MonthlyAmounts.Add(new MonthlyAmount()
{ MonthYear = now,
DebtType = "Visa", DebtAmount = 1.2M, });
MonthlyAmounts.Add(new MonthlyAmount()
{ MonthYear = now.Subtract(TimeSpan.FromDays(2)),
DebtType = "Visa", DebtAmount = 42.0M, });
MonthlyAmounts.Add(new MonthlyAmount()
{ MonthYear = now.Subtract(TimeSpan.FromDays(31)),
DebtType = "MC", DebtAmount = 50.95M, });
MonthlyAmounts.Add(new MonthlyAmount()
{ MonthYear = now.Subtract(TimeSpan.FromDays(33)),
DebtType = "Visa", DebtAmount = 3.1415M, });
//insert above `codedMonthlyAmounts` & `latest` queries here.
var format = "{0} @ {1:MMM} {1:yyyy} = {2:#,##0.00}";
foreach (var x in latest)
{
Console.WriteLine(format,
x.DebtType,
x.MonthYear,
x.DebtAmount);
}
Console.WriteLine("Total = {0:#,##0.00}",
latest.Sum(l => l.DebtAmount));
输出的测试代码:
Visa @ Dec 2010 = 43.20
MC @ Nov 2010 = 50.95
Total = 94.15
让我知道这是否是你想要的。
我不明白“根据上次报告的每月债务数量获得总额的债务”,如果我们不需要猜测债务数额的存储位置,那将会很好。 – VVS 2010-12-14 23:49:43
对不起,我想我应该添加更多的db结构...虽然下面的第一个答案看起来像它可能工作(现在尝试)。 – CraigF 2010-12-16 00:00:33
我有2个表格,一个是债务类型清单(Id和Name),另一个是每个债务的债务清单(DebtId int32,“MonthYear”datetime,“DebtAmount”decimal)。 – CraigF 2010-12-16 00:17:28