2017-01-05 152 views
0

我用Linqer到SQL轉換到LINQ,但結果是不一樣的 我的SQL查詢:使用計數返回比SQL查詢不同的結果

Select ChuyenNganh.ChuyenNganhID,ChuyenNganh.TenChuyenNganh,SoLuong= count(BaiBao.ChuyenNganhID) 
from BaiBao right join ChuyenNganh on ChuyenNganh.ChuyenNganhID = BaiBao.ChuyenNganhID 
group by ChuyenNganh.ChuyenNganhID, ChuyenNganh.TenChuyenNganh 

轉換到LINQ

var queryChuyenNganh = from t in myPhanLoaiTaiLieuDataContext.ChuyenNganhs 
            join t0 in myPhanLoaiTaiLieuDataContext.BaiBaos on new { ChuyenNganhID = t.ChuyenNganhID } equals new { ChuyenNganhID = Convert.ToInt32(t0.ChuyenNganhID) } into t0_join 
            from t0 in t0_join.DefaultIfEmpty() 
            group t by new 
            { 
             t.ChuyenNganhID, 
             t.TenChuyenNganh 
            } into g 
            select new 
            { 
             ChuyenNganhID = (System.Int32)g.Key.ChuyenNganhID, 
             g.Key.TenChuyenNganh, 

             SoLuong =(Int32)g.Count() 
            }; 

結果:

的LINQ

enter image description here

SQL

enter image description here

誰能幫我?

+0

的't0_join.DefaultIfEmpty()'將是0 count行,因此返回一個默認值1 – Frogger

+0

我想在你的sql查詢你是否正確地加入BaiBao與ChuyenNganh並且在你Linq你正確的加入ChuyenNganh與BaiBao。爲了正確或者左連接的順序問題,你正在計算基數(BaiBao.ChuyenNganhID) – Saadi

回答

0

不同之處在於,在LINQ統計所有記錄時,SQL對外部連接表中的列BaiBao.ChuyenNganhID中的非空值進行計數。

你需要讓LINQ計數非空值,以及:

var queryChuyenNganh = from t in myPhanLoaiTaiLieuDataContext.ChuyenNganhs 
    join t0 in myPhanLoaiTaiLieuDataContext.BaiBaos 
     on new { t.ChuyenNganhID } equals new { ChuyenNganhID = Convert.ToInt32(t0.ChuyenNganhID) } into t0_join 
    from t0 in t0_join.DefaultIfEmpty() 
    group new {T=t, NonNull=t0.ChuyenNganhID != null} by new 
    { 
     t.T.ChuyenNganhID, 
     t.T.TenChuyenNganh 
    } into g 
    select new 
    { 
     ChuyenNganhID = (System.Int32)g.Key.ChuyenNganhID, 
     g.Key.TenChuyenNganh, 
     SoLuong =(Int32)g.Count(x => x.NonNull) 
    }; 
+0

我不這麼認爲。在g到g之後,g不包含BaiBao.ChuyenNganhID,因此g沒有非空值 –

+0

@DiênCông您是否閱讀並理解了答案中的查詢? – dasblinkenlight

1

最有可能的SQL查詢可以在LINQ改寫沒有group by但簡單的LINQ GroupJoin

但隨着轉換的主要問題是,SQL COUNT(expr)不計算NULL值,並沒有直接的LINQ相等的,所以無論是有條件的CountSum需要(我個人更喜歡後者,因爲它通常會帶來更好的SQL )。

所以,在你查詢所需的最小變化是

group t by newgroup t0 by new

SoLuong =(Int32)g.Count()SoLuong = g.Sum(t0 => t0 != null ? 1 : 0)

附:如本文開頭提到的,我會給一個嘗試以下LINQ查詢:

var queryChuyenNganh = 
    from t in myPhanLoaiTaiLieuDataContext.ChuyenNganhs 
    join bb in myPhanLoaiTaiLieuDataContext.BaiBaos 
    on t.ChuyenNganhID equals bb.ChuyenNganhID into t_BaiBaos 
    select new 
    { 
     t.ChuyenNganhID, 
     t.TenChuyenNganh, 
     SoLuong = t_BaiBaos.Count() 
    };