最大值和另一列值

时间:2013-09-26 13:41:38

标签: sql-server-2008

我有一个包含4列的表格:产品,公司,收入,单位

除此之外,我希望在一列中使用不同的产品名称,max,min,avg,std dev用于收入,该产品的单位是单独的列,以及在另一列中生成该产品的最大收入的公司名称。在下一个我想要收入的百分比(在该产品的总收入中)。

我想要表格中的每一件产品。有关如何做的任何建议吗?

我可以获得max,min,avg,std dev和product但无法获得该公司的名称,该名称与该产品的最大收入相对应。

2 个答案:

答案 0 :(得分:1)

对于与最高收入相对应的公司,您可以在select语句中执行类似的操作。

select company from table where revenue =
(select max(revenue) from table where products = currentProduct)

答案 1 :(得分:0)

您可以使用ranking functions

WITH CTE AS
(
    SELECT products, company, revenue, units,
      MaxRevenue = MAX(revenue) OVER (PARTITION BY products),
      MinRevenue = MIN(revenue) OVER (PARTITION BY products),
      AvgRevenue = AVG(revenue) OVER (PARTITION BY products),
      STDEV_Revenue = STDEV(revenue) OVER (PARTITION BY products),
      MaxUnits = MAX(units) OVER (PARTITION BY products),
      MinUnits = MIN(units) OVER (PARTITION BY products),
      AvgUnits = AVG(units) OVER (PARTITION BY products),
      STDEV_Units = STDEV(units) OVER (PARTITION BY products),
      Percent_Revenue = Max(Revenue)OVER (PARTITION BY products)/SUM(Revenue) OVER (PARTITION BY products),           
      ProductNum = ROW_NUMBER()OVER(PARTITION BY products ORDER BY products)
    FROM dbo.TableName  
)
SELECT * FROM CTE 
WHERE ProductNum = 1