在linq上编写sql查询时遇到问题

时间:2011-10-07 07:09:23

标签: c# sql linq

我有一个sql查询,它返回所有帐户,在结果表的顶部,我有共享相同文档的帐户。下面的查询工作得很好,坚持在linq上实现相同的逻辑存在问题。请帮忙!

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

1 个答案:

答案 0 :(得分: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 };