简体   繁体   中英

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. 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)

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.
  • I removed the vendor name and price from the GROUP BY for the same reason.
  • AVG , MIN , and MAX are bad names for columns, because these are SQL keywords.

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

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

Note, Gordon's advice re column naming

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