我正在和linq一起努力学习语法,我无法弄清楚如何进行以下简单查询
SELECT DISTINCT
user.firstname,
user.lastname,
COUNT(invoice.amount),
SUM(invoice.amount)
FROM
company_user
INNER JOIN
user
ON
company_user.user_id = user.user_id
INNER JOIN
invoice
ON
invoice.user_id= invoice.user_id
WHERE
company_user.company_id = 1
GROUP BY
user.firstname,
user.lastname,
GO
将此转化为linq的任何帮助都会很棒。
答案 0 :(得分:16)
你所追求的问题应该非常接近:
var query =
from cu in company_user
where cu.company_id == 1
join u in user on cu.user_id equals u.user_id
join i in invoice on u.user_id equals i.user_id
group i.amount by new
{
u.firstname,
u.lastname,
} into gs
select new
{
firstname = gs.Key.firstname,
lastname = gs.Key.lastname,
count = gs.Count(),
sum = gs.Sum(),
};
享受!
答案 1 :(得分:4)
由于op提到了学习语法,这里有一个流畅的版本:
company_user
.Where(x => x.company_id == 1)
.Join(
user,
x => x.user_id,
x => x.user_id,
(o,i) => new {
FirstName = i.firstName,
LastName = i.lastName,
InvoiceCount = invoice.Count(y => y.user_id == o.user_id),
InvoiceSum = invoice.Where(y => y.user_id == o.user_id).Sum(y => y.amount)
}
).GroupBy(x => new { x.FirstName, x.LastName })
.Distinct()
答案 2 :(得分:0)
有大多数linq函数的例子,如果你不知道,如果有人没有,我可能会在以后为你写。
答案 3 :(得分:0)
我认为您的加入条款存在差异 - 您在user_id上加入了自己的发票。我假设您打算将此加入用户?
无论如何,这是我最好的镜头:
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)
}
对于LINQ建议,我绝对建议您下载并使用LINQPad。我一直用它来测试没有Visual Studio的LINQ语句。它也会将您的LINQ语句转换为SQL,这可能是您特别感兴趣的。
编辑: Enigmativity的声明与您的请求相比更接近我的声明。我没有偶然发现我合作的例子中的列分组。