如何用C#编写SQL查询格式

[ad_1]

专家您好,我有一系列 SQL 查询格式的代码,在这段代码中我将 3 个表连接在一起。
这是我的代码:

select distinct(t.UserNO),t.UserName,s.TotalDays from User_Tbl as t 
join( select ChartNo from Chart_Rest_Tbl) as f ON t.UserNO = f.ChartNo join(select ChartNO, sum(Days) as TotalDays from Chart_Rest_Tbl
group by ChartNo) AS s ON f.ChartNO = s.ChartNo

现在我想用C#格式编写上面的代码,就像这样的代码(我的意思是如何用C#格式编写上面的代码,下面的代码只是一个例子,我与下面的代码无关):

var st = (from s in db.Worker_Tbl
   join o in db.User_Tbl on s.WorkerNO equals o.UserNO
   where o.UserNO == txtsearch1
   select new { s.WorderId, o.UserName, s.WorkerNO, s.GPEntireDate, s.GPExpiredDate, s.GPCount }).ToList();

我尝试过的:

我不知道怎么写

SUM(Days)

C# 格式或者如何写

distinct

谢谢您的宝贵时间<3

解决方案1

以下是来自 SQL 查询的 C# LINQ 格式。

C#
var query = from t in dbContext.User_Tbl
            join f in dbContext.Chart_Rest_Tbl.Select(x => x.ChartNo).Distinct() on t.UserNO equals f
            join s in dbContext.Chart_Rest_Tbl.GroupBy(x => x.ChartNo)
                                               .Select(g => new { ChartNO = g.Key, TotalDays = g.Sum(x => x.Days) })
            on f equals s.ChartNO
            select new
            {
                UserNO = t.UserNO,
                UserName = t.UserName,
                TotalDays = s.TotalDays
            };
var result = query.Distinct().ToList();

要修改或进一步参考,您可以尝试以下工具将 SQL 查询转换为 C# 中的 LINQ 格式:
LINQPad – .NET 程序员的游乐场[^]
首页 – Linqer[^]

解决方案2

C#
string sql = @"
select distinct(t.UserNO),t.UserName,s.TotalDays from User_Tbl as t 
join( select ChartNo from Chart_Rest_Tbl) as f ON t.UserNO = f.ChartNo join(select ChartNO, sum(Days) as TotalDays from Chart_Rest_Tbl
group by ChartNo) AS s ON f.ChartNO = s.ChartNo
" ;

[ad_2]

コメント

标题和URL已复制