forik
forik

Reputation: 149

Having problems with writing sql query on linq

I have an SQL query which returns all accounts and in the top of the result table I have accounts which share same documents. Query below works just fine, but there is a problem implementing the same logic on 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

Upvotes: 2

Views: 148

Answers (1)

George Duckett
George Duckett

Reputation: 32448

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

Note: You could probably change the subquery to a join on DocID but i've left as is, so you can see the similarity between the SQL and the LINQ.

Example with a join:

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

Upvotes: 3

Related Questions