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
I don’t think it’s currently possible to do the
count(distinct x)part.This is the closest I got:
But it produces exactly the same SQL as:
Which is:
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.