gpt4 book ai didi

c# - LINQ to SQL - 连接、分组和求和

转载 作者:行者123 更新时间:2023-12-02 21:56:17 24 4
gpt4 key购买 nike

我有以下 SQL 按预期工作:

SELECT  p.ACCT_ID AS [Acct], 
a.ACCT_NAME AS [AcctName],
p.PD_NO AS [Period],
p.FY_CD AS [FY],
SUM(CUR_AMT) AS [CActual],
SUM(CUR_BUD_AMT) AS [CBudget],
SUM(YTD_AMT) AS [YActual],
SUM(YTD_BUD_AMT) as [YBudget]
FROM BudgetTotals p
INNER JOIN BudgetAccounts a
ON p.ACCT_ID = a.ACCT_ID WHERE p.ACCT_ID IN ('610','620','630','634','641','642','643','644','646','665','620','DFC','DFR','DGN','DTX')
AND FY_CD == "2013"
AND PD_NO == 12
AND POOL_NO == 23
GROUP BY p.ACCT_ID, a.ACCT_NAME, p.PD_NO, p.FY_CD;

我正在尝试使用以下内容将上述内容转换为 Linq to Sql:

var query = from p in db.POOL_SIE_SUPPORTs
join c in db.ACCTs on p.ACCT_ID equals c.ACCT_ID
where arr.Contains(p.ACCT_ID) && p.POOL_NO == 23 && p.FY_CD == "2013" && p.PD_NO == 12
group p by p.ACCT_ID into s
select new
{
Account = s.Key,
AccountName = from acct in db.ACCTs select new { acct.ACCT_NAME },
CTDActual = string.Format("{0:C}", s.Sum(y => y.CUR_AMT)),
CTDBudget = string.Format("{0:C}", s.Sum(y => y.CUR_BUD_AMT)),
YTDActual = string.Format("{0:C}", s.Sum(y => y.YTD_AMT)),
YTDBudget = string.Format("{0:C}", s.Sum(y => y.YTD_BUD_AMT))
};

如何让我的查询返回 AccountName 列?

最佳答案

假设每个给定的 Acct_Id 只有一个 Acct_Name,否则您将获得多条记录,就像进行分组时一样:

var query = from p in db.POOL_SIE_SUPPORTs
join c in db.ACCTs on p.ACCT_ID equals c.ACCT_ID
where arr.Contains(p.ACCT_ID) && p.POOL_NO == 23 && p.FY_CD == "2013" && p.PD_NO == 12
group p by new { p.ACCT_ID, p.ACCT_NAME } into s
select new
{
Account = s.Key.ACCT_ID,
AccountName = s.Key.ACCT_NAME,
CTDActual = string.Format("{0:C}", s.Sum(y => y.CUR_AMT)),
CTDBudget = string.Format("{0:C}", s.Sum(y => y.CUR_BUD_AMT)),
YTDActual = string.Format("{0:C}", s.Sum(y => y.YTD_AMT)),
YTDBudget = string.Format("{0:C}", s.Sum(y => y.YTD_BUD_AMT))
};

关于c# - LINQ to SQL - 连接、分组和求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17730716/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com