如果存在相同的值(例如给定的产品名称),如何在SQL Server中合并行?

时间:2018-07-30 18:41:56

标签: sql-server linq

如标题所述,我正在使用SQL Server。

这是我当前的查询

select  
    p.[Name], p.[Price], prli.Quantity, (p.Price * prli.Quantity) as subtotal
from 
    PurchaseRequests as pr
join 
    PurchaseRequestLineItems as prli on pr.Id = prli.PurchaseRequestId
join 
    Products as p on prli.ProductId = p.ID
where 
    p.VendorID = 2 and pr.Status = 'Approved';

我的结果看起来像这样

query result

如何让我的查询在每次发生时都将纸箱合并在一起,而不是每次都有该产品的有效订单时都没有一行,而是将其合并为一行?

我用LinQ弄清楚了,但是我想做一个存储过程以使其更有效率。

Linq语法如下:

在这里可以用多种方法给猫去皮,这就是我最初想出的方式。我还刚刚学习了使用Iqueriables使其更快的方法,但是我真的想创建一个存储过程,主要用于练习。

 public JsonRequest All(int? Id)
        {
            JsonRequest json = new JsonRequest();
            VendorOrder vendorOrder = new VendorOrder();
             vendorOrder.Prlis = db.PurchaseRequestLineItems.Where(li => li.Products.VendorID == Id && li.PurchaseRequest.Status == "Approved").ToList();
             vendorOrder.Total = vendorOrder.Prlis.Sum(li => li.Quantity * li.Products.Price);
            List<string> ProductNames = new List<string>();
            List<string> ProductPartNum = new List<string>();
            List<decimal> Quantity = new List<decimal>();
            List<decimal> Price = new List<decimal>();
            List<PurchaseRequestLineItem> lineItems = new List<PurchaseRequestLineItem>();
            string partNum = "";
            string name = "";

            foreach(var product in vendorOrder.Prlis)
            {
                name = product.Products.Name;
                partNum = product.Products.Partnum;
                if (!ProductPartNum.Contains(partNum))
                {
                  var x =  vendorOrder.Prlis.FindAll(p => p.Products.Partnum == partNum).ToList();
                    ProductNames.Add(name);
                    ProductPartNum.Add(partNum);
                    Quantity.Add(x.Sum(p => p.Quantity));
                    Price.Add(x.Sum(p => p.Quantity * p.Products.Price));
                }
            }
            vendorOrder.Quant = Quantity;
            vendorOrder.Cost = Price;
            vendorOrder.productName = ProductNames;

1 个答案:

答案 0 :(得分:4)

您需要一个GROUP BY子句。这将为每个项目提供一行,但是如果该项目具有多个不同的价格,则每个[名称+价格]都将位于单独的行上:

SELECT  p.[Name] ,
        p.[Price] ,
        Quantity = SUM(prli.[Quantity]) ,
        Subtotal = SUM(( p.[Price] * prli.[Quantity] ))
FROM    PurchaseRequests AS pr
        JOIN PurchaseRequestLineItems AS prli ON pr.Id = prli.PurchaseRequestId
        JOIN Products AS p ON prli.ProductId = p.ID
WHERE   p.VendorID = 2
        AND pr.Status = 'Approved'
GROUP BY [Name], [Price] ;