T-SQL分组分组

时间:2011-01-04 19:36:06

标签: tsql group-by partitioning

我在SQL server 2008中有下表。请帮助获得预期的输出

alt text

感谢。

CREATE TABLE [dbo].[Test]([Category] [varchar](10) NULL,[Value] [int] NULL,
[Weightage] [int] NULL,[Rn] [smallint] NULL ) ON [PRIMARY]

insert into Test values ('Cat1',310,674,1),('Cat1',783,318,2),('Cat1',310,96,3),('Cat1',109,917,4),('Cat2',441,397,1),('Cat2',637,725,2),('Cat2',460,742,3),('Cat2',542,583,4),('Cat2',601,162,5),('Cat2',45,719,6),('Cat2',46,305,7),('Cat3',477,286,1),('Cat3',702,484,2),('Cat3',797,836,3),('Cat3',541,890,4),('Cat3',750,962,5),('Cat3',254,407,6),('Cat3',136,585,7),('Cat3',198,477,8),('Cat4',375,198,1),('Cat4',528,351,2),('Cat4',845,380,3),('Cat4',716,131,4),('Cat4',781,919,5)

3 个答案:

答案 0 :(得分:1)

按类别平均重量

SELECT
   Category,
   AVG(Value),
   SUM(CASE WHEN RN<4 THEN Weightage ELSE 0 END) / (NULLIF(SUM(CASE WHEN RN<4 THEN 1 ELSE 0 END), 0))
FROM
   MyTable
GROUP BY
   Category

整套的平均重量

SELECT
   M.Category,
   AVG(Value),
   foo.AvgWeightage
FROM
   MyTable M
   CROSS JOIN
   (SELECT AVG(Weightage) As AvgWeightage FROM MyTable WHERE Rn < 4) foo
GROUP BY
   M.Category, foo.AvgWeightage

答案 1 :(得分:1)

简单:)

  SELECT Category,  
        AVG(Value) AS AvgValue, 
        AVG(CASE WHEN RN< 4 THEN (Weightage) END ) AS AvgWeightage
  FROM Test
  GROUP BY Category

答案 2 :(得分:0)

试试这个

SELECT AvgValue.Category, AvgValue.AvgValue, AvgWeight.Weight
FROM(
(SELECT c.Category, 
        AVG(c.Value) AS AvgValue
    FROM Test c
    GROUP BY Category) AvgValue
INNER JOIN 
(SELECT Category, AVG(Weightage) AS Weight
    FROM Test
    WHERE Rn < 4
    GROUP BY Category) AvgWeight
ON AvgValue.Category = AvgWeight.Category)