简体   繁体   中英

LINQ to SQL Grouping and Counting

I have searched for solution, but nothing similar. My problem is that I want to select data from database, group it by UserID and Count it by Status id

Users

UserID
Name

Appointments

UserID
ClientID
Status
StartDate

Status can be active=1, canceled=2, done=3

This is how I will display results.

结果表

Thanks in advance.

In you question you say you want to group on UserId , but in the output you show Name . This query will group on both. You might want to adjust it to your needs.

from u in tblUsers
join a in tblAppointments on u.UserID equals a.UserID
group a by new { u.UserID, u.Name } into g
select new
{
    Name     = g.Key.Name,
    Active   = g.Count (x => x.Status == 1),
    Canceled = g.Count (x => x.Status == 2),
    Done     = g.Count (x => x.Status == 3)
}

(this will handle the case if two users have the same name though)

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