对Linq的相对简单的SQL查询(带分组)

时间:2016-01-25 21:52:20

标签: c# .net sql-server linq

我有一个sql语句,需要修改为Linq的任何正确形式(查询语法和/或lambda) - 任何想法将不胜感激:

SELECT DISTINCT
    CUSTOMER_NUM, CUSTOMER_NAME, 
    COUNT(*) AS 'COUNT',
    SUM(CASE WHEN State = 'State1' THEN 1 ELSE 0 END) AS 'State1Count',
    SUM(CASE WHEN State = 'State2' THEN 1 ELSE 0 END) AS 'State2Count',
    ISNULL(SUM(USD_TOTAL_MRC_AMT), 0) AS 'USD_TOTAL_MRC_AMT_SUM'        
FROM Table1
WHERE
 (
    USERID = @UserId   //@UserId is a parameter passed into the stored procedure
)
GROUP BY CUSTOMER_NUM, CUSTOMER_NAME
ORDER BY
    CUSTOMER_NAME

以下是LinqPad迄今为止所做的工作:

Table1.GroupBy(i => 1).Select(g => new { 
Total = g.Count(i => i.State == "AM Re-Rate Pool" || i.State == "AM Renewal Pool"),
ReRates = g.Count(i => i.State == "State1"),
Renewals = g.Count(i => i.State == "State2
});

谢谢!

1 个答案:

答案 0 :(得分:0)

以下是我使用方法语法的方法。

Table1.Where(t => t.UserId = userId)
      .OrderBy(t => t.CustomerName)
      .GroupBy(t => new {t.Customer_Num, t.Customer_Name})
      .Select(grp => new
      {
          grp.Key.Customer_Num,
          grp.Key.Customer_Name,
          Count = grp.Count(),
          State1Count = grp.Where(t => t.State = "State1").Count(),
          State2Count = grp.Where(t => t.State = "State2").Count(),
          USD_TOTAL_MRC_AMT_SUM = grp.Sum(t => t.USD_TOTAL_MRC_AMT_SUM) ?? 0
      })
      .Distinct();