2012-03-19 95 views
0

假定我們如下表具有:SQL申請合計平均有條件

index value 
1  55 
2  66 
3  77 
1  88 
3  99 

如何可以總結(值)時索引= 1個或索引= 3,並且平均(值)當索引= 2的一個選擇聲明?

+0

什麼是您預期的結果(以表格形式)? – 2012-03-19 15:23:47

回答

3

輕鬆:

SELECT index, CASE WHEN index IN (1, 3) THEN SUM(value) ELSE AVG(value) END 
FROM yourTable 
GROUP BY index 
+0

謝謝,我以前不知道有病例陳述。 – karpar 2012-03-19 16:39:25

+0

不客氣! – 2012-03-19 18:03:07

1
SELECT sum(value) as agg, 
     'S' as aggregateType 
FROM DaTAble 
WHERE index IN (1, 3) 

UNION ALL 

SELECT avg(value) as agg, 
     'A' as aggregateType 
FROM DaTAble 
WHERE index = 2