1

我有一个类似的 SQL 代码;

Select GroupName, sum(LineAmount) as Total, WeekNumber,
    ROW_NUMBER() over (partition by WeekNumber order by sum(LineAmount) desc) as RowNum
from
    Invoices
where
    month(InvoiceDate)=month(getdate())
group by
    GroupName,WeekNumber

我想将其转换为 LINQ,但没有运气。我正在使用 LINQ to Object。任何帮助,将不胜感激。TIA

编辑:这是一些示例数据和预期结果。

public class Invoice
{
    public string GroupName { get; set; }
    public int LineAmount { get; set; }
    public int WeekNum { get; set; }
}

   List<Invoice> theData = new List<Invoice>();
    theData.Add(new Invoice { GroupName = "A", LineAmount = 1, WeekNum = 1});
    theData.Add(new Invoice { GroupName = "A", LineAmount = 2, WeekNum = 1 });
    theData.Add(new Invoice { GroupName = "A", LineAmount = 3, WeekNum = 1 });
    theData.Add(new Invoice { GroupName = "A", LineAmount = 2, WeekNum = 2 });
    theData.Add(new Invoice { GroupName = "A", LineAmount = 3, WeekNum = 2 });
    theData.Add(new Invoice { GroupName = "A", LineAmount = 4, WeekNum = 2 });
    theData.Add(new Invoice { GroupName = "B", LineAmount = 4, WeekNum = 1 });
    theData.Add(new Invoice { GroupName = "B", LineAmount = 3, WeekNum = 1 });
    theData.Add(new Invoice { GroupName = "B", LineAmount = 7, WeekNum = 2 });
    theData.Add(new Invoice { GroupName = "B", LineAmount = 6, WeekNum = 2 });
    theData.Add(new Invoice { GroupName = "B", LineAmount = 5, WeekNum = 2 });

在此处输入图像描述

我已经从我的第一个查询中删除了“where”,因为它目前不是问题。

4

3 回答 3

1
theData
.GroupBy(g => new {g.GroupName, g.WeekNum}, (key, gg) => new {key.GroupName, key.WeekNum, Total = gg.Sum(g => g.LineAmount)})
.GroupBy(g => g.WeekNum, (weekNum, gg) => gg.OrderByDescending(g => g.Total).Select((g,i) => new {g.GroupName, g.Total, g.WeekNum, RowNum = i}))
.SelectMany(g => g)
于 2012-08-08T07:11:26.663 回答
0

您尚未指定所需的语言。这是 C# 中的代码

int index = 0;
var filteredInvoices = (from i in invoices
where i.InvoiceDate.Month == DateTime.Now().Month
group i by new { i.GroupName, i.WeekNumber }
into ig
select new {i.GroupName, Total = ig.Sum(i => i.LineAmount), i.WeekNumber, RowNum = ++index}).OrderByDescending(n => n.Total);

filtersInvoices 应该有你想要的结果。此外,我假设 i.InvoiceDate 的类型为 DateTime。

于 2012-08-07T20:27:55.200 回答
0

Serg Rogovtsev 的回答给了我预期的结果。下面的代码就是我所做的。不知道哪个表现更好,但结果是一样的。

(theData.GroupBy(f => new { f.GroupName, f.WeekNum})
                .Select(r => new {r.Key.WeekNum, r.Key.GroupName, Total = r.Sum(f => f.LineAmount)}))
                .GroupBy(r => new {r.WeekNum}).SelectMany(
                    g =>
                    g.OrderByDescending(f => f.Total).Select(
                        (f, index) => new { f.GroupName, f.Total, f.WeekNum, Ix = index + 1 })) 
于 2012-08-08T08:16:12.297 回答