Linq to SQL:Group By和Sum()

时间:2010-08-09 23:35:14

标签: asp.net vb.net linq-to-sql

我对linq很新,所以这应该很容易回答,但我很难找到答案。

我有以下LINQ语句,它执行简单的linq查询并在asp.net Web表单上分配结果值标签:

        Dim db As New MeetingManagerDataContext
    Dim q = From s In db.vwRoomAvailabilities _
                Where s.MeetingID = lblMeetingID.Text _
                Select s.AllRequestedSingles, s.AllRequestedDoubles, s.AllBookedSingles, s.AllBookedDoubles, SinglesNeeded = s.AllRequestedSingles - s.AllBookedDoubles, DoublesNeeded = s.AllRequestedDoubles - s.AllBookedDoubles

    lblSinglesRequested.Text = "Singles Requested: " & q.FirstOrDefault.AllRequestedSingles
    lblSinglesBooked.Text = "Singles Booked: " & q.FirstOrDefault().AllBookedSingles
    lblSinglesNeeded.Text = "Singles Needed: " & q.FirstOrDefault().SinglesNeeded
    lblDoublesRequested.Text = "Doubles Requested: " & q.FirstOrDefault().AllRequestedDoubles
    lblDoublesBooked.Text = "Doubles Booked: " & q.FirstOrDefault().AllBookedDoubles
    lblDoublesNeeded.Text = "Doubles Needed: " & q.FirstOrDefault().DoublesNeeded

最初,只有一行结果,你可以看到我正在使用FirstOrDefault()来获取效果很好的单个值。但是设计已经改变,查询现在可以返回多行。我现在需要按上面的MeetingID分组,并对每个选定的列进行SUM(即s.AllRequestedDoubles)。

我发现了大量的分组和总结样本,但似乎没有一个适合这种情况。

您能否帮我修改上面的LINQ以对结果值求和而不是仅显示第一行结果值?

1 个答案:

答案 0 :(得分:5)

试试这个

From s In db.vwRoomAvailabilities
Where s.MeetingID = lblMeetingID.Text
Group by s.MeetingID 
into SumAllRequestedDoubles = sum(s.AllRequestedDoubles),
     SumAggregate2 = sum(s.SomeField2),
     SumAggregate3 = sum(s.SomeField3)
Select SumAllRequestedDoubles, SumAggregate2, SumAggregate3

这将使您开始在该单个列上执行SUM。

您需要将每个SUM'd列投影到一个新的别名列(就像我上面所做的那样)。

此外,由于您不熟悉LINQ-SQL,请查看LinqPad - 它会震撼您的世界。