多个联接后跟多个where,group和order LinqToSql

时间:2016-09-26 20:42:05

标签: c# sql-server linq linq-to-sql

所以我在Sql中有一个查询,它有多个连接后跟一个左连接,其中,组和一个顺序,我需要使用LinqToSql转换它。

    SELECT ...
           COUNT(d.column3) as column3
           ...

    FROM table_s s
    JOIN table_d d
         ON s.column1 = d.column1
         AND s.column2 = d.column2
    JOIN table c
            ON s.column1 = c.column1
            AND s.column2 = c.column2
            AND d.column3 = c.column3
            AND s.column4 = c.column4
        JOIN table_i i
            ON s.column1 = i.column1
            AND c.column5 = i.column5
        JOIN table_t t
            ON i.column1 = t.column1
            AND i.column2 = t.column2
        LEFT JOIN table_t1 t1
            ON t1.column1 = i.column1
            AND t1.column2 = i.column2
            AND t1.column3 =  'variable'
            AND t1.column4 = variable2
    WHERE s.column1 = variable2
        AND s.column2 = variable3
    GROUP BY s.column2, i.column5, t1.column7, t.column8,
         c.column7, i.column7, s.column7 
    ORDER BY s.column7 DESC,
        s.column2 DESC;

所以我设法编写了大部分Linq查询并且它正在工作,但是我遇到了大组的问题。并使用COUNT语法

    var query = from s in db.table_s                           
    join d in db.table_d
        on new { A=s.column1, B=s.column2 }
           equals new { A=d.column1, B=d.column2 }
    join c in db.table_c
        on new { A=s.column1, B=s.column2, C=d.column3 , D=s.column4 }
           equals new { A=c.column1, B=c.column2, C=c.column3, D=c.column4 }
    join i in db.table_i
        on new { s.column1, c.column5  }
           equals new { i.column1, i.column5  }
    join t in db.table_t
         on new { A=i.column1, B=i.column5  }
           equals new { A=t.column1, B=t.column2 }
    join t1 in db.table_t1
         on new { A=i.column1, B=i.column5 , C="variable1", D=variable2  }
           equals new { A=t1.column1, B=t1.column2, C=t1.column3, D=t1.column4   } into gj
    from t1 in gj.DefaultIfEmpty()
         where (s.column1 == variable2) && (s.column2 == variable3)
    //group s by s.column2, i.column5 , t1.colT, t.colH, c.colN, i.colF, s.colD
    //group s by new {s.column2, i.column5 , t1.colT, t.colH, c.colN, i.colF, s.colD } into grp

    orderby s.column7 descending, s.column2 descending
          select new
          {
             ...
          };

注意:我不想将其拆分为多个查询

查询此问题的正确语法是什么?谢谢!

0 个答案:

没有答案