简体   繁体   English

如果我们需要在SQL Server 2014中聚合特定行时如何使用聚合函数

[英]How to use aggregate function if we need aggregate of specific rows in SQL Server 2014

I have the following code which has 7 rows. 我有下面的代码,其中有7行。 I would like to take avg, min, max of the product name column that are same (for example: I have 3 products with a name of 'Shoes' that are same and their costs are 50, 45, 60. I have one product named 'Hat' with a cost of 50. Now I would like to take average of 3 common rows ie 50, 45, 60 and it should display 51.66. For the other row, it should display 50 and so forth) 我想在商品名称栏中输入平均,最小值,最大值,它们是相同的(例如:我有3个商品名称相同的“鞋”,其成本分别为50、45、60。我有一个商品命名为“帽子”,成本为50。现在,我想取3个普通行的平均值,即50、45、60,并应显示51.66。对于另一行,应显示50,依此类推)

My problem is if I run below query it display the avg, max, min of same row instead of taking avg, min, max of rows that are same. 我的问题是,如果我在查询下面运行,它将显示同一行的平均值,最大值,最小值,而不是显示相同行的平均值,最小值,最大值。

SELECT 
    PRODUCT.ProductName,
    Vendor.VendorName, VendorProduct.Cost,
    AVG(COST) AS AVG, 
    MIN(COST) AS MIN,
    MAX(COST) AS MAX
FROM
    PRODUCT
JOIN
    VendorProduct ON VendorProduct.ProductID = PRODUCT.ProductID
JOIN
    Vendor ON Vendor.VendorID = VendorProduct.VendorID
GROUP BY
    PRODUCT.ProductName, VendorProduct.Cost, Vendor.VendorName

Any help is appreciated. 任何帮助表示赞赏。

I am guessing that you want: 我猜您想要:

SELECT p.ProductName,
       AVG(vp.COST) AS AVG, MIN(vp.COST) AS MIN, MAX(vp.COST) AS MAX
FROM PRODUCT p join
     VendorProduct vp
     on vp.ProductID = p.ProductID
GROUP BY p.ProductName;

Notes: 笔记:

  • I have qualified all the column names using abbreviations for the table. 我已经使用表的缩写限定了所有列名。
  • I removed the vendor name from the SELECT , because you want the averages by product. 我从SELECT删除了供应商名称,因为您需要按产品求平均值。
  • I removed the vendor name and price from the GROUP BY for the same reason. 由于相同的原因,我从GROUP BY删除了供应商名称和价格。
  • AVG , MIN , and MAX are bad names for columns, because these are SQL keywords. AVGMINMAX是列的错误名称,因为它们是SQL关键字。

Change 更改

AVG(cost) as avg

To

AVG(cost) OVER(PARTITION BY productname) as [avg]

Make the same change (adding an OVER clause) to the other aggregates and also remove the GROUP BY line entirely 对其他聚合进行相同的更改(添加OVER子句),并完全删除GROUP BY行

This will give you the same number of rows as you're getting now, but the aggregates will repeat for every identical value of product name. 这将为您提供与现在相同的行数,但是汇总将针对每个相同的产品名称值重复进行。 You also get to keep the vendor details 您还可以保留供应商详细信息

What is it? 它是什么? In sqls it's called a window function; 在sqls中,它称为窗口函数; a way of grouping a data set and implicitly connecting the grouped results to the detail rows, without losing the detail rows' detail. 一种对数据集进行分组并隐式将分组结果连接到明细行的方法,而不会丢失明细行的明细。 MSDN will have a lot to say about them if your curiosity is piqued 如果您的好奇心激起,MSDN将对他们说很多话

Note, Gordon's advice re column naming 注意,戈登的建议重新命名列

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

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