J4X
J4X

Reputation: 119

LINQ Left Join and GroupBy

Let say I have this SQL Query:

SELECT 
    PromotionSlot.StaffFName, 
    SUM(PromotionSlot.Max_Occupancy) AS TOTAL,
    SUM(DISTINCT(Booking.Quantity)) AS Occupied
From PromotionSlot 
LEFT JOIN Booking
ON PromotionSlot.StaffID=Booking.StaffID
GROUP BY  PromotionSlot.StaffFName

Result:

|StaffFName    |TOTAL    |Occupied|
-----------------------------------
|Jason         |13       |1       |
|John Doe      |9        |0       |      
|Marry Jane    |7        |2       |

This is my DB Table:

PromotionSlot TABLE: ID(PK),Max_Occupancy,StaffFName..., StaffID(FK)
Booking TABLE: ID(PK), Quantity...,StaffID(FK) 

How can I translate it into LINQ? This is my attempt:

var staffData = 
    (from ps in dc.PromotionSlots
     join b in dc.Bookings on ps.StaffID = b.StaffID
     group ps by ps.StaffFName into NewGroup
     select new dataView
     {
         StaffFName = NewGroup.Key,
         Total = NewGroup.Sum(a => a.Max_Occupancy),

         //problem:
         //Occupied = NewGroup.Sum(b => b.Quantity)
     }

Plan to have Occupied = NewGroup.Sum(b => b.Quantity) but when I try to point the b to the quantity column from Booking table it shows error(red-line) and I think the problems comes from group ps by ps.StaffFName into NewGroup makes it available for PromotionSlot table instead of Booking table. But I totally have no idea how to solve this!

Upvotes: 0

Views: 2432

Answers (1)

Hari Prasad
Hari Prasad

Reputation: 16956

Based on your SQL query, what you need is take Distinct quanties and Sum them.

var staffData = 
    (from ps in dc.PromotionSlots
     join b in dc.Bookings on ps.StaffID = b.StaffID into slots
     from slot in slots.DefaultIfEmpty()
     group new {ps, slot} by ps.StaffFName into NewGroup
     select new dataView
     {
         StaffFName = NewGroup.Key,
         Total = NewGroup.Sum(a => a.ps!=null? a.ps.Max_Occupancy: 0),

         //problem:
         Occupied = NewGroup.Select(x=>x.slot.Quantity).Distinct().Sum()
     }

Upvotes: 2

Related Questions