2014-01-16 78 views
1

如何查詢交叉表等報告? 例如我的表如下所示生成交叉表報告im oracle?

+----+--+--+--+ 
|Name|v1|v2|v3| 
+----+--+--+--+ 
|A |12|10|5 | 
+----+--+--+--+ 
|B |10|5 |20| 
+----+--+--+--+ 

現在我的查詢應該給我下?

+-----+--+--+--+ 
|Name |v1|v2|v3| 
+-----+--+--+--+ 
|A |12|10|5 | 
+-----+--+--+--+ 
|B |10|5 |20| 
+-----+--+--+--+ 
|Total|22|15|25| 
+-----+--+--+--+ 

感謝您的幫助

+0

請問MySQL還是oracle? –

回答

1

使用UNION加入行:(MySQL的代碼)

SELECT name,v1,v2,v3 FROM my_table 
UNION ALL 
SELECT "total",sum(v1) as v1 ,sum(v2) as v2 ,sum(v3) as v3 FROM my_table; 

看着它在這裏工作:sqlfiddle

1

下面是相似的示例,您查詢的MySQL數據庫:

 
SELECT year, SUM(profit) FROM sales GROUP BY year WITH ROLLUP; 
+----+-----------+ 
|year|SUM(profit)| 
+----+-----------+ 
|2000|4525  | 
+----+-----------+ 
|2001|3010  | 
+----+-----------+ 
|NULL|7535  | 
+----+-----------+ 
+0

類似的作品也適用於Oracle,使用'GROUP BY ROLLUP(year)' –