Reputation: 3406
How would you write this exact SQL query with the new Linq-to-NHibernate Provider (3.x)
SELECT Post.Title, COUNT(DISTINCT Comment.UserId)
FROM Post
INNER JOIN Comment ON Post.Id = Comment.PostId
GROUP BY Post.Title
Here is some SQL if you want to make some tests
DECLARE @Post Table(Id int identity(1,1), Title varchar(200))
DECLARE @Comment Table(Id int identity(1,1), PostId int, Comment varchar(200), UserId int)
DECLARE @PostId int
INSERT INTO @Post(Title)
VALUES ('Test')
SELECT @PostId = SCOPE_IDENTITY()
INSERT INTO @Comment(PostId, Comment, UserId)
VALUES (@PostId, 'Test Comment', 1)
INSERT INTO @Comment(PostId, Comment, UserId)
VALUES (@PostId, 'Test Comment 2', 1)
INSERT INTO @Comment(PostId, Comment, UserId)
VALUES (@PostId, 'Test Comment 3', 2)
INSERT INTO @Post(Title)
VALUES ('Test 2')
SELECT @PostId = SCOPE_IDENTITY()
INSERT INTO @Comment(PostId, Comment, UserId)
VALUES (@PostId, 'Test Comment', 1)
INSERT INTO @Comment(PostId, Comment, UserId)
VALUES (@PostId, 'Test Comment 2', 2)
INSERT INTO @Comment(PostId, Comment, UserId)
VALUES (@PostId, 'Test Comment 3', 3)
SELECT Post.Title, COUNT(DISTINCT Comment.UserId)
FROM @Post Post
INNER JOIN @Comment Comment ON Post.Id = Comment.PostId
GROUP BY Post.Title
Upvotes: 2
Views: 2079
Reputation: 52735
I don't think it's currently possible to do the count(distinct x)
part.
This is the closest I got:
from comment in session.Query<Comment>()
group comment by comment.Post.Title
into g
select new
{
Title = g.Key,
Count = g.Select(x => x.UserId).Distinct().Count()
};
But it produces exactly the same SQL as:
from comment in session.Query<Comment>()
group comment by comment.Post.Title
into g
select new
{
Title = g.Key,
Count = g.Count()
};
Which is:
SELECT Post.Title, COUNT(*)
FROM Comment
LEFT JOIN Post ON Post.Id = Comment.PostId
GROUP BY Post.Title
You should post an issue to http://jira.nhforge.org. There's a lot of work going on with the Linq provider and there's a good chance to get this construct supported in the near future.
Upvotes: 2