简体   繁体   中英

How to group by and calculate sum and select where is less than given amount in SQL Server / C# Linq

How to group by year and calculate the sum, select where TotalCollected is less than given amount in SQL Server or C# Linq.

I want to group data by Year and Refno , calculate the sum and select Where the sum result is less than -100000.

My current code look like this in SQL Server

SELECT 
    Year, Refno, SetaCode,
    SUM(TotalCollected) AS TotalCollected
FROM 
    transactions 
GROUP BY 
    Year, Refno, TypeCode  
ORDER BY
    Year, Refno, TypeCode;

The current output is like this:

   | 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         |
   +------+-----------+-----------+----------------+

Any help please even if you can reply with C# linq query code it fine.

Please help me guys I am stuck.

Linq version:

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM