简体   繁体   English

如何在数据库查询结果中按列值求和

[英]How to SUM up results by column value in db query result

My database has a sales table with entries like so: 我的数据库有一个销售表,其条目如下:

_____________________________________
| id |  title_id   |       qty      |
-------------------------------------
| 0  |  6          |        10      |
-------------------------------------
| 1  | 5           |        5       |
-------------------------------------
| 2  |  6          |        2       |
-------------------------------------

Title_id is Foreign key pointing to Titles table which is as follows: Title_id是指向Titles表的外键,如下所示:

_____________________________________
| id |  title_id   |       title    |
-------------------------------------
| 0  |  5          |       Soda     |
-------------------------------------
| 1  |  6          |      Coffee    |
-------------------------------------

I want to find top 5 sold products wich means i need to calculate the qty value for each product for all it's entried in sales table then order the result by qty in descending order and limit the select to 5. 我想找到销售量最高的5种产品,这意味着我需要为销售表中输入的所有产品计算每种产品的数量值,然后按数量降序排列结果并将选择范围限制为5。

However I'm new to C# ASP.NET and somewhat new to SQL. 但是,我是C#ASP.NET的新手,而SQL是新手。 I dont know how to do this with LINQ. 我不知道如何用LINQ做到这一点。 This is my code so far: 到目前为止,这是我的代码:

        var getIds = (from sale in db.sales
                      join tit in db.titles on sale.title_id equals tit.title_id
                      group sale by sale.qty into result
                      orderby result.Sum(i => i.qty) descending
                      select new Publication 
                      { 
                        PubID = sales.title_id, Title = tit.title
                      }
                      ).Take(5);

Assuming you have a navigation property Sale.Title , something like this should do: 假设您具有导航属性Sale.Title ,则应执行以下操作:

var tops = 
  db.Sales
    .GroupBy( o => o.Title )
    .Select( o => new { Title = o.Key, Sum = o.Sum( x => x.Quantity ) } )
    .OrderByDescending( o => o.Sum )
    .Take( 5 )
    .ToList();

tops is then a list of an anonymous type with two properties: the Title object and the sum of the quantities. 然后tops是具有两个属性的匿名类型的列表: Title对象和数量的总和。


You can then get the values like this: 然后,您可以获取如下所示的值:

foreach( var top in tops )
{
  int titleId = top.Title.title_id;
  string title = top.Title.title;
  int sumOfQuantities = top.Sum;
  ...

If you just want the top Title objects, can can select them like this: 如果只需要顶部的Title对象,可以像这样选择它们:

List<Title> topTitles = tops.Select( o => o.Title ).ToList();
var result= (from p in sales
              let k = new
              {
                  Name = p.Name
              }
              group p by k into t
              orderby Name descending
              select new
              {
                  Name = t.Name,
                  Qty = t.Sum(p => p.Qty)
              }).Take(5);

If the entries in the Sales table are more than one per item (ie: in your example you have 'Soda' 10 + 'Soda' 2, then you need to GroupBy() , using the name as the key (or it's related id if it's in another table), but not the qty. 如果“销售”表中每个项目的条目多于一个(即:在您的示例中,您有“ Soda” 10 +“ Soda” 2,则需要使用名称作为键,或者是GroupBy() (或其相关ID (如果在另一个表中),但不包括数量。

var topSales = db.sales.GroupBy(x => x.title)
                       .Select(g => new 
                                    { 
                                       Title = g.Key, 
                                       Qty = g.Sum(x => x.qty)
                                    })
                       .OrderByDescending(x => x.Qty)
                       .Select(x => new Publication 
                                    { 
                                       PubID = x.Title.title_id, 
                                       Title = x.Title.title1
                                    })
                       .Take(5)
                       .ToList();

Note that I've omitted the join statement assuming that you have a foreign key between sales.title_id -> title.id, and you are using LINQ to SQL. 请注意,假设您在sales.title_id-> title.id之间有一个外键,并且您正在使用LINQ to SQL,那么我已经省略了join语句。 Also note that I've avoided using the query syntax in favor of the chained method syntax, I think it's much clear in this use case (although not always true, ie: cross-joins). 还要注意,我避免使用查询语法来支持链接方法语法,在这种用例中,我认为这很清楚(尽管并非总是如此,即:交叉联接)。

Also, SQL and LINQ have some similarities but don't let the names of clauses/methods fool you, LINQ is not SQL, IMHO, Microsoft just tried to make people comfortable by making it look similar ;) 此外,SQL和LINQ有一些相似之处,但不要让子句/方法的名称欺骗您,LINQ不是SQL,恕我直言,Microsoft只是试图通过使它看起来相似来使人们感到舒服;)

EDIT : fixed GroupBy() 编辑 :固定的GroupBy()

var result= (from p in sales
              let k = new
              {
                  Name = p.Name
              }
              group p by k into t
              select new
              {
                  Name = t.Name,
                  Qty = t.Sum(p => p.Qty)
              }).OrderByDescending(i => i.Qty).Take(5);

You need to look at GroupBy; 您需要查看GroupBy; this will give you what you need 这会给你你所需要的

http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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