2010-12-03 39 views
2

你會怎麼寫新的LINQ到NHibernate的提供者這個確切的SQL查詢(3.X)COUNT DISTINCT - 內部連接 ​​- 集團/與之新的LINQ到NHibernate的提供商

SELECT Post.Title, COUNT(DISTINCT Comment.UserId) 
FROM Post 
INNER JOIN Comment ON Post.Id = Comment.PostId 
GROUP BY Post.Title 

下面是一些SQL如果你想使一些測試

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 
+0

你有多遠? StackOverflow用於幫助解決問題,而不是用於工作。沒有冒犯,但更多的上下文將有助於在這種情況下;) – 2010-12-03 02:47:22

+0

鑑於這個問題很簡單,我花時間來產生整個SQL,我認爲這個問題不值得這種評論。我剛開始使用NHibernate,我甚至不知道從哪裏開始。我認爲這個問題對任何NHibernate專家都很容易... – W3Max 2010-12-03 03:00:51

回答

2

我不認爲這是目前可能做count(distinct x)部分。

這是我得到的最接近:

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

但它產生完全相同的SQL爲:

from comment in session.Query<Comment>() 
group comment by comment.Post.Title 
     into g 
     select new 
      { 
       Title = g.Key, 
       Count = g.Count() 
      }; 

那就是:

SELECT Post.Title, COUNT(*) 
FROM Comment 
LEFT JOIN Post ON Post.Id = Comment.PostId 
GROUP BY Post.Title 

你應該張貼一個問題http://jira.nhforge.org。 Linq提供商有很多工作要做,並且很有可能在不久的將來得到支持。