2011-10-07 73 views
2

我有一個sql查詢返回所有帳戶,並在結果表頂部我有共享相同文檔的帳戶。下面的查詢工作得很好,堅持有一個問題在linq上實現相同的邏輯。請幫忙!在LINQ上編寫SQL查詢時遇到問題

select 
(
    select 
     COUNT(*) 
    from Signs X, Signs Y 
    where X.AccountID = 2 and Y.AccountID = A.ID and X.DocID = Y.DocID 
), 
* 
from 
    Accounts A 
where 
    A.ID != 2 
order by 1 desc 
+0

你會寫你有什麼問題呢?請更具體一些。 – Reniuz

回答

3
var result = from A in Accounts 
      where A.ID != 2 
      select new { Count = (from X in Signs 
            from Y in Signs 
            where X.AccountID == 2 && 
            Y.AccountID == A.ID && 
            X.DocID == Y.DocID 
            select 1).Count(), 
          A }; 

注意:你也許可以改變子查詢上DocID一個join但我已經保留原樣,這樣你就可以看到SQL和LINQ之間的相似性。

例與聯接:

var result = from A in Accounts 
      where A.ID != 2 
      select new { Count = (from X in Signs 
            join Y in Signs on X.DocID equals Y.DocID 
            where X.AccountID == 2 && 
            Y.AccountID == A.ID 
            select 1).Count(), 
          A }; 
+0

不應該X.DocID = Y.DocID是'X.DocID == Y.DocID'(強調'==')? – Aamir

+0

這正是我需要的!你說過可以使用連接編寫它。你能證明一下嗎?其實我試着加入,但我失敗了。謝謝! – forik

+0

Aamir:謝謝,修復.. –