SQL:计数列并显示总结果

时间:2014-07-02 09:13:19

标签: mysql sql select count sum

这是我目前在我桌上的选择:

SELECT count(*) as Titel, KuenstlerName FROM Bild GROUP BY KuenstlerName;
+-------+---------------+
| Titel | KuenstlerName |
+-------+---------------+
|     3 | Klee          |
|     1 | Klingt        |
|     1 | Marc          |
|     6 | Picasso       |
|     1 | van Gogh      |
+-------+---------------+

是否有办法添加新的行/列或只显示一条消息,该消息返回“Titel”列的总值。

例如:

+-------+---------------+
| Titel | KuenstlerName |
+-------+---------------+
|     3 | Klee          |
|     1 | Klingt        |
|     1 | Marc          |
|     6 | Picasso       |
|     1 | van Gogh      |
|    12 | Total         |
+-------+---------------+

+-------+---------------+-----+
| Titel | KuenstlerName |Total|
+-------+---------------+-----+
|     3 | Klee          |  12 |
|     1 | Klingt        |     |
|     1 | Marc          |     |
|     6 | Picasso       |     |
|     1 | van Gogh      |     |
+-------+---------------+-----+

+-------+---------------+
| Titel | KuenstlerName |
+-------+---------------+
|     3 | Klee          |
|     1 | Klingt        |
|     1 | Marc          |
|     6 | Picasso       |
|     1 | van Gogh      |
+-------+---------------+
Total: 12

感谢您的帮助!

4 个答案:

答案 0 :(得分:1)

可能不是最优雅的解决方案,但这可行:

SELECT count(*) as Titel, KuenstlerName 
FROM Bild 
GROUP BY KuenstlerName
UNION ALL
SELECT count(*) as Titel, 'Total' AS KuenstlerName 
FROM Bild

(有人在我打字的时候跳入了几乎相同的解决方案,UNION ALL应该比UNION单独快一点)。

答案 1 :(得分:0)

SELECT count(*) as Titel, KuenstlerName FROM Bild GROUP BY KuenstlerName
UNION 
SELECT count(*),'Total' FROM Bild 

答案 2 :(得分:0)

SELECT KuenstlerName, count(*) as Titel FROM Bild GROUP BY KuenstlerName
UNION 
SELECT "Total:" AS KuenstlerName, count(*) AS Titel FROM Bild

答案 3 :(得分:0)

试试这个:

SELECT sum(titel),coalesce(KuenstlerName,'Total') FROM testdb.titel GROUP BY KuenstlerName with rollup;

感谢。

添加了结果截图。

enter image description here