2012-02-03 26 views
1

我的SQL語句是如何實現這個SQL塊包含(有,加入和GROUP BY)使用LINQ

SELECT c.type,c.title,c.datereg, d.ranknum 
FROM T_News AS c 
    INNER JOIN (
    SELECT a.id, COUNT(*) AS ranknum 
    FROM T_News AS a 
      INNER JOIN T_News AS b 
      ON (a.type = b.type) 
      AND (a.datereg >= b.datereg) 
    GROUP BY a.id 
    HAVING COUNT(*) <= 3 
) AS d ON (c.id = d.id) 
ORDER BY c.type, d.ranknum 

,我得到http://rickosborne.org/blog/2008/01/sql-getting-top-n-rows-for-a-grouped-query/

爲獲得TOP N行的分組查詢

EFUnitOfWork EF = new EFUnitOfWork(); 
T_NewsRepository News = new T_NewsRepository(); 
News.UnitOfWork = EF; 
var query = 
    from news1 in News.All() 
    join news2 in News.All() 
     on news1.type equals news2.type into resjoin 
    group news1 by news1.id into idgroup 
    where idgroup.Count() <= 3 
    select new { idgroup }; 

var x = query.ToList(); 

我沒有得到任何錯誤,但「哪裏idgroup.Count()< = 3」,沒有工作,我得到的所有行以dB爲結果

+0

你得到了什麼錯誤? – doogle 2012-02-03 12:14:22

+0

我沒有得到任何錯誤,但「其中idgroup.Count()<= 3」沒有工作,我得到所有行數據庫作爲結果 – amir 2012-02-03 13:04:38

回答

1

將其分解爲最小的組件,然後再編寫較大的查詢。讓我們先從最裏面的查詢是有道理的:

SELECT 
    a.id, COUNT(*) AS ranknum 
FROM 
    T_News AS a 
     INNER JOIN T_News AS b ON 
      (a.type = b.type) AND 
      (a.datereg >= b.datereg) 
GROUP BY 
    a.id 
HAVING 
    COUNT(*) <= 3 

我想這個轉換爲:

// Items with counts/ranknum 
var ranknum = 
    from a in News.All() 
    join b in News.All() on 
     a.type equals b.type 
    where 
     a.datereg > b.datereg 
    group by a.id into g 
    select new { g.Key as id, g.Count() as ranknum }; 

// Filter the ranknum. 
ranknum = ranknum.Where(rn => rn.ranknum <= 3); 

然後加入與外部查詢:

SELECT 
    c.type,c.title,c.datereg, d.ranknum 
FROM 
    T_News AS c 
     INNER JOIN (<sub-query from above>) as d ON 
      c.id = d.id 
ORDER BY 
    c.type, d.ranknum 

這部分變得簡單,因爲它只是兩個現有查詢之間的連接。

var query = 
    from c in News.All() 
    join rn in ranknum on c.id = rn.id 
    orderby c.type, rn.ranknum 
    select new { c.type, c.title, c.datereg, rn.ranknum }; 

機會是,LINQ到實體產生這種情況的SQL會看起來真的醜,而且很可能是低效的,在這種情況下,你可能要考慮將這種邏輯在存儲過程然後通過LINQ-to-Entities調用(對於更復雜的查詢通常是這樣)。