gpt4 book ai didi

sql - Linq to SQL Group by 和 Sum in Select

转载 作者:行者123 更新时间:2023-12-04 10:53:59 29 4
gpt4 key购买 nike

我需要将该 SQL 查询转换为 Linq:

SELECT
SUM([ArticleAmount]) as amount
,[ArticleName]
FROM [DB].[dbo].[OrderedArticle]

group by articlename

order by amount desc

我尝试了以下代码,但在“a.ArticleName”处出现错误,指出“ArticleName”的定义将丢失。
var sells = orderedArt
.GroupBy(a => a.ArticleName)
.Select(a => new {Amount = a.Sum(b => b.ArticleAmount),Name=a.ArticleName})
.OrderByDescending(a=>a.Amount)
.ToList();

你们中有人知道如何解决这个问题吗?

谢谢你的帮助!

最佳答案

您收到此错误是因为分组没有返回 IEnumerable<OrderedArticle>但是 IEnumerable<IGrouping<string, OrderedArticle>>
您需要更改代码才能使用 a.Key :

var sells = orderedArt
.GroupBy(a => a.ArticleName)
.Select(a => new { Amount = a.Sum(b => b.ArticleAmount), Name = a.Key})
.OrderByDescending(a => a.Amount)
.ToList();

关于sql - Linq to SQL Group by 和 Sum in Select,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13988800/

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