Linq to SQL to aggregate data by week

时间:2017-04-10 01:18:41

标签: c# linq linq-to-sql

I have a table with columns of Date, Buy, Sell, InStock, and a table with date and corresponding week of the year (please see below for the tables). And want to aggregate the columns of Buy and Sell by Week.

There is some function in LINQ to SQL that aggregates data by month or by year, but I could not find any function to aggregate data by week.

Could someone help me with LINQ to SQL query to get the data using the two tables? Any suggestion is appreciated.

The first two tables are what I have, and I want to get the third table by joining the two tables using LINQ query.


Sales Table

Date Buy Sell InStock
1/1/2017 5 2 123
1/2/2017 4 4 123
1/3/2017 3 7 119
1/4/2017 4 2 121
1/5/2017 3 2 122
1/6/2017 5 2 125
1/7/2017 3 2 126
1/8/2017 7 5 128
1/9/2017 5 8 125
1/10/2017 2 2 125
1/11/2017 1 2 124
1/12/2017 5 2 127
1/13/2017 2 2 127
1/14/2017 3 2 128
1/15/2017 4 3 129
1/16/2017 5 2 132
… … … …


DateToWeek Table

Date WeekOfTheYear
1/1/2017 1
1/2/2017 1
1/3/2017 1
1/4/2017 1
1/5/2017 1
1/6/2017 1
1/7/2017 1
1/8/2017 2
1/9/2017 2
1/10/2017 2
1/11/2017 2
1/12/2017 2
1/13/2017 2
1/14/2017 2
1/15/2017 3
1/16/2017 3
1/17/2017 3
1/18/2017 3
1/19/2017 3
… …

Table I want to get:

Date Week Buy Sell InStock
1/1/2017 1 27 21 123
1/8/2017 2 25 25 128
1/15/2017 3 22 28 122
… … … …

2 个答案:

答案 0 :(得分:0)

也许这样的查询。我无法测试...

from st in db.SalesTable 
join w in db.DateToWeek on st.DateBuy equals w.Date
group new {st, w} by new {w.Date, w.WeekOfTheYear} into gr
select new 
{
    Date = gr.Key.Date,
    Week = gr.Key.WeekOfTheYear,
    Buy = gr.Sum(x=>x.Buy),
    Sell = gr.Sum(x => x.Sell),
    InStock = gr.Sum(x=>x.Instock)
}

答案 1 :(得分:0)

            var query = (from c in
            (from st in db.SalesTable 
                  join w in db.DateToWeek on st.DateBuy equals w.Date
                  group new {st, w} by new {w.WeekOfTheYear} into gr
                     select new 
                               {
                               Week = gr.Key.WeekOfTheYear,
                               Buy = gr.Sum(x=>x.Buy),
                               Sell = gr.Sum(x => x.Sell),
                               InStock = gr.Sum(x=>x.Instock)
                             })
                     group c by c.Week into gr2
                     select new
                     {
                         Date = gr2.Min(x=>x.Date),
                         Buy = gr2.Sum(x => x.Buy),
                         Sell = gr2.Sum(x => x.Sell),
                     }

            ).OrderBy(x => x.Date);