tags:

views:

210

answers:

2

Can anyone LINQ the following SQL?

I've been on this for two hours now and am no closer to getting this than I was when I started.

SELECT ArticleId, sum(Amount) AS VoteCount
FROM  ArticleVotes INNER JOIN
Votes ON ArticleVotes.voteId = Votes.id
GROUP BY ArticleVotes.articleId
ORDER BY VoteCount DESC

Tables as follows;

ArticleVotes: ArticleId, VoteId

Votes: id, amount

+2  A: 
from articleVote in ArticleVotes
join vote in Votes on art.voteId equals vote.id
group articleVote by artarticleVote.articleId
select new 
{
ArticleId = art.ArticleID,
VoteCount = Votes.Sum(vote.amount)
}
orderby VoteCount

I'm not entirely sure about the orderby part, for the matter, I'm not sure about the rest either, as I'm not in the position to test it. If it doesn't work, don't blame me please :)

Update: Using the OP's work:

from artVotes in ArticleVotes
join vote in Votes on artVotes.VoteId equals vote.Id
group artVotes by artVotes.ArticleId into g
let totalAmount = g.Sum(p => p.Vote.Amount)
orderby totalAmount descending
select new { ArticleId = g.Key, total = totalAmount}


Edit fixed the orderby to use descending ordering.

Thanks to the op giving me reason to use the let operator, and finally realizing its beauty. You helped me immensely with your question, just by asking it. +1 for that.

Femaref
Femaref, thanks for the answer but I'm getting ") or end of expressions expected" after articleVote.ArticleId.
griegs
You need to add a comma: "ArticleId = art.ArticleId, VoteCount = ..." also need to fix the order by. I'll answer to show it all.
Reed Copsey
Um, where did Reed's answer go? Looks to have been removed. No matter, even that had the same problem in that it was expecting a ) at the enmd of the group line.
griegs
+1 for getting me really close but I still need to order by. I have posted an answer but it needs the order by added.
griegs
That last Update worked a treat. Thanks for your help Femaref
griegs
Was a pleasure, you helped me also to understand more. I feel in love with LINQ the first time I've seen it, but I'm just at the surface of using it. Thanks for giving me an oppurtunity to dive into it more and understand the concept.
Femaref
Yeah LINQ is pretty sweet though sometimes I feel I get bogged down. Looking at your reply, I've now learnt a few things like grouping and the new keyword of "let". Huge.
griegs
The funny thing is, I also was looking for something like your problem, I was fully aware of the "let" keyword, but I couldn't make the connection apperently.
Femaref
Well, I'm glad I could help! :)
griegs
A: 

This is what i have now but it's missing the order by the total.

from artVotes in ArticleVotes
join vote in Votes on artVotes.VoteId equals vote.Id
group artVotes by artVotes.ArticleId into g
select new { ArticleId = g.Key, total = g.Sum(p => p.Vote.Amount)}
griegs