[英]How to group by and calculate sum and select where is less than given amount in SQL Server / C# Linq
如何按年份分组并计算总和,选择在SQL Server或C#Linq中TotalCollected
小于给定数量的位置。
我想按Year
和Refno
对数据进行Refno
,计算总和,然后选择总和结果小于-100000的地方。
我当前的代码在SQL Server中看起来像这样
SELECT
Year, Refno, SetaCode,
SUM(TotalCollected) AS TotalCollected
FROM
transactions
GROUP BY
Year, Refno, TypeCode
ORDER BY
Year, Refno, TypeCode;
当前输出如下:
| Year | Refno | TypeCode | TotalCollected |
+------+-----------+-----------+----------------+
| 2015 | G30714630 | 16 | -534713,04 |
| 2015 | G30738332 | 16 | -16471 |
| 2015 | G00746893 | 11 | -441770,75 |
| 2015 | G10712596 | 11 | -1254,53 |
| 2015 | G30711221 | 21 | -740616,41 |
| 2015 | G50769901 | 21 | -1131 |
| 2014 | G30714630 | 16 | -26575,4 |
| 2014 | G10703033 | 11 | -122156,62 |
| 2013 | G00750516 | 21 | -31578,38 |
| 2013 | G30775855 | 21 | -9032,19 |
| 2013 | G50749525 | 21 | 0 |
| 2013 | G30714630 | 16 | -0,4 |
| 2013 | G10703033 | 11 | 527,17 |
+------+-----------+-----------+----------------+
即使您可以使用C#linq查询代码答复,也请帮忙。
请帮助我,我被困住了。
Linq版本:
var result = transactions
.GroupBy(t => new { t.Year, t.Refno, t.SetaCode })
.Select(grp => new
{
Year = grp.Key.Year,
Refno = grp.Key.Refno,
SetaCode = grp.Key.SetaCode,
TotalCollected = grp.Sum(x => x.TotalCollected)
})
.Where(r => r.TotalCollected < -100000)
.OrderBy(r => r.Year).ThenBy(r => r.Refno).ThenBy(r => r.SetaCode)
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.