SQL聚合按列分组

时间:2017-03-13 09:06:48

标签: sql

我有一张看起来像这样的表:

price is_a is_b is_c ...
  300    1    0    1 ...
  500    0    1    0 ...
  200    1    1    1 ...
  400    0    1    1 ...

我现在想要选择每个“is_”属性的平均价格:

avg(price)    is_a     is_b     is_c
  250         1        0        0
  367         0        1        0
  300         0        0        1

我目前正在使用以下查询,这显然会返回所有属性的所有可能组合(在这种情况下,与上面完全相同的表):

SELECT avg(price), is_a, is_b, is_c, ... FROM table GROUP BY is_a, is_b, is_c, ...

2 个答案:

答案 0 :(得分:2)

您需要使用联合。但是,您将计算两次出现次数:

SELECT avg(price), 1, 0, 0 ... FROM table WHERE is_a = 1
UNION
SELECT avg(price), 0, 1, 0 ... FROM table WHERE is_b = 1
UNION
SELECT avg(price), 0, 0, 1 ... FROM table WHERE is_c = 1

正如我所说,如果有匹配is_a is_b的记录,它们的价格将计入第一列和第二列。

答案 1 :(得分:0)

Use CTE to get your result :

CREATE TABLE #table(price INT,is_a INT,is_b INT,is_c INT)
INSERT INTO #table(price ,is_a ,is_b ,is_c)
SELECT 300,1,0,1 UNION ALL
SELECT 500,0,1,0 UNION ALL
SELECT 200,1,1,1 UNION ALL
SELECT 400,0,1,1 

;WITH _CTEAvg ( Avgprice , is_a , is_b , is_c ) AS 
(
  SELECT AVG(price) , 1 , 0 , 0
  FROM #table
  WHERE is_a = 1
  GROUP BY is_a
  UNION ALL
  SELECT AVG(price) , 0 , 1 , 0
  FROM #table
  WHERE is_b = 1
  GROUP BY is_b
  UNION ALL
  SELECT AVG(price) , 0 , 0 , 1
  FROM #table
  WHERE is_c = 1
  GROUP BY is_c
 )

 SELECT * FROM _CTEAvg