2012-08-07 138 views
1

我有一个SQL代码像;LINQ RowNumber,Aggregate(Sum)和GroupBy

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来对象。任何帮助,将不胜感激。 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 }); 

enter image description here

我已删除“其中”从我第一次查询其此刻不存在问题。

回答

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) 
+1

'RowNum = i'应该是'RowNum = i + 1'来给出预期的结果。 – sloth 2012-08-08 07:18:33

+0

谢谢Serg,你的解决方案给了我预期的结果。我已经找到了一个解决方案。我不知道哪一个表现最好!任何想法将不胜感激。 – bsaglamtimur 2012-08-08 08:20:41

+0

@bsaglamtimur他们或多或少相同,而选择是个人喜好和可读性的问题。就我而言,我不喜欢嵌套查询。 – 2012-08-08 08:30:49

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); 

filteredInvoices应该有你想要的结果。另外我假设i.InvoiceDate是DateTime类型的。

+0

我已编辑我的问题。你能否根据我的样本数据来回顾你的答案。 – bsaglamtimur 2012-08-08 06:40:40

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 }))