Query : แสดงค่าและผลรวมในคอลัมน์ (Sum) โดยไม่ต้องใช้ union all
posted on 01 Oct 2009 13:50 by peekanung in Knowledgeเมื่อค่าใน Table T1 มีดังนี้
X Y
---------- ----------
1 2
2 3
3 4
4 5
5 6
ต้องการ Query ค่าจาก Table T1 ให้แสดงผลดังนี้
X Y X+Y
---------- ---------- ----------
1 2 3
2 3 5
3 4 7
4 5 9
5 6 11
15 20 35
ซึ่งปกติ สามารถทำได้โดยใช้ Union all โดยใช้ Statement ดังนี้
select x,y,x+y from t
union all
select sum(x),sum(y),sum(x+y) from t ;
แต่ถ้าไม่ต้องการใช้ Union all สามารถแทนด้วย Statement นี้
select decode( grouping(rowid), 0, null, 1, 'the end' ) label,sum(x), sum(y), sum(x+y)
from t
group by rollup(rowid);
จะได้ผลดังนี้
LABEL SUM(X) SUM(Y) SUM(X+Y)
------ ---------- ---------- ----------
1 2 3
2 3 5
3 4 7
4 5 9
5 6 11
the end 15 20 35
อ้างอิง http://asktom.oracle.com