如何在group by子句中获得平均价格

时间:2017-01-17 02:19:17

标签: sql-server group-by average

我运行此操作以查明是否有更多OEMNumber的相同记录:

USE [ISTABLocalDB]
SELECT OEMNumber, COUNT(*)
FROM [file].[ItemPart]
GROUP BY
    OEMNumber
HAVING 
    COUNT(*) > 1

enter image description here

然后我如何找到列price1,price2和price3的平均价格,并将其与oemnumber一起分组,如果有超过1个相同的记录

SELECT TOP 1000 
      [OEMNumber]
      ,[Price1]
      ,[Price2]
      ,[Price3]
  FROM [ISTABLocalDB].[file].[ItemPart]

enter image description here

2 个答案:

答案 0 :(得分:0)

您想要以下内容吗?

SELECT TOP 1000 [OEMNumber],SUM(ISNULL(c.price,0))/COUNT(NULLIF(c.price,0)) AS av
FROM [ISTABLocalDB].[file].[ItemPart]
CROSS APPLY(VALUES(Price1),(Price2),(Price3)) c(price)
GROUP BY OEMNumber

这是一个示例:

;WITH tb(Id,n1,n2,n3,n4,n5,n6)AS(
   SELECT 1,6,1,2,3,4,5 UNION
   SELECT 2,0,0,2,0,4,5 UNION
   SELECT 3,0,1,2,0,4,5 UNION
   SELECT 4,0,1,0,3,0,5 UNION
   SELECT 5,0,1,0,3,0,5 UNION
   SELECT 6,0,1,0,0,4,5

)
SELECT id,SUM(ISNULL(c.n,0)) AS total,COUNT(NULLIF(c.n,0)) AS cnt
       ,SUM(ISNULL(c.n,0))*1.0/COUNT(NULLIF(c.n,0)) AS av FROM tb
CROSS APPLY(VALUES(n1),(n2),(n3),(n4),(n5),(n6)) c(n)
GROUP BY id
id          total       cnt         av
----------- ----------- ----------- ---------------------------------------
1           21          6           3.500000000000
2           11          3           3.666666666666
3           12          4           3.000000000000
4           9           3           3.000000000000
5           9           3           3.000000000000
6           10          3           3.333333333333

答案 1 :(得分:0)

试试这个。

USE [ISTABLocalDB]

SELECT 
    OEMNumber, AVG(price1) AS Price1, AVG(price2) AS Price2, AVG(price3) AS Price3
FROM 
    [file].[ItemPart]
GROUP BY
    OEMNumber
HAVING 
    COUNT(*) > 1