Simple sql to Linq query with group by and aggregate functions

后端 未结 4 999
萌比男神i
萌比男神i 2021-02-02 01:51

I\'m fighting with linq trying to learn the syntax and I can\'t figure out how to do the following simple query

SELECT DISTINCT
    user.firstname,
    user.last         


        
4条回答
  •  囚心锁ツ
    2021-02-02 02:37

    I think you have a discrepancy in your join clause -- you're inner joining invoice to itself on user_id. I assume that you intended to join this to user?

    In any case, here's my best shot:

    from inv in invoices
    group inv by new { inv.user_id } into userInv
    join usr in users on userInv.Key.user_id equals usr.user_id
    where usr.company_user.company_id = 1
    select new
    {
        usr.firstname,
        usr.lastname,
        amount = inv.Count(),
        sum = inv.Sum(amt => amt.amount)
    }
    

    As for LINQ suggestions, I'd definitely suggest you download and play around with LINQPad. I use it all the time to test LINQ statements without Visual Studio. It'll convert your LINQ statements to SQL as well, which is probably of particular interest to you.

    Edit: Enigmativity's statement is a lot closer to what you requested than mine is. I hadn't stumbled onto the column grouping in the examples I worked with.

提交回复
热议问题