LINQ to SQL 分组和计数

发布于 2024-12-31 22:33:12 字数 320 浏览 5 评论 0原文

我已经寻找解决方案,但没有类似的。 我的问题是我想从数据库中选择数据,按用户 ID 对其进行分组并按状态 ID 对其进行计数

用户

UserID
Name

约会

UserID
ClientID
Status
StartDate

状态可以是活动 = 1,取消 = 2,完成 = 3

这就是我显示结果的方式。

结果表

提前致谢。

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.

Results table

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

新人笑 2025-01-07 22:33:12

在您的问题中,您说您想要对 UserId 进行分组,但在输出中您显示 Name。此查询将对两者进行分组。您可能想根据您的需要进行调整。

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)
}

(如果两个用户具有相同的名称,这将处理这种情况)

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文