简体   繁体   中英

Linq SQL join on same table with group and sum

I've had a look through StackOverflow and have tried things from a few posts but am totally stuck. Basically I have the query below (tested in LinqPad), which, for the "sum" values gives me the same value twice. What I actually want is a join to the same table, group by date and to show the sum of what is essentially the same column (Value), from the joined table and the original table.

I have found that you can't use aliases (ie in SQL FieldName as 'NewFieldName') in LINQ, so somehow I need to sum up t.Value and p.Value, and show those next to SiteID and EntryDate in my results.

(from p in DailyStatistics
join t in DailyStatistics on new { p.EntryDate, p.SiteID} equals new { t.EntryDate, t.SiteID} 
where t.Metric == "MyVisitors" 
&& p.Metric == "MyVisits" 
&& p.EntryDate >= DateTime.Parse("2013-08-15" ) 
&& p.EntryDate <= DateTime.Parse("2013-08-21" ) 
group p by new { t.SiteID, p.EntryDate } into s
orderby s.Key.EntryDate
select new {s.Key.SiteID, s.Key.EntryDate, SumVisits = s.Sum(t => t.Value), SumVisitors = s.Sum(x => x.Value) })

This one in particular I tried, but couldn't quite adapt it to my needs: SQL multiple joins and sums on same table

Any ideas would be happily accepted :-)

Edit

I forgot the where clause.

DailyStatistics
.Join
(
    DailyStatistics,
    x=>new{x.EntryDate, x.SiteID},
    x=>new{x.EntryDate, x.SiteID},
    (o,i)=>new 
    {
        VisitorEntry=i.Metric,
        VisitEntry=o.Metric,
        VisitorDate = i.EntryDate ,
        VisitDate = o.EntryDate ,
        i.SiteID,
        VisitorValue = i.Value,
        VisitValue = o.Value
    }
)
.GroupBy
(
    x=>
    new
    {
        x.SiteID,
        x.VisitDate
    }
)
.Where
(
    x=>
    x.VisitorEntry == "MyVisitors" &&
    x.VisitEntry== "MyVisits" &&
    x.VisitDate >= DateTime.Parse("2013-08-15")  &&
    x.VisitDate <= DateTime.Parse("2013-08-21")
)
.Select
(
    x=>
    new
    {
        x.Key.SiteID, 
        x.Key.VisitDate, 
        SumVisits = s.Sum(t => t.VisitValue ), 
        SumVisitors = s.Sum(x => x.VisitorValue ) 
    }
)
.OrderBy
(
    x=>x.VisitDate
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM