我想将我的专栏与'Gesamt'对齐:
SELECT k.KUNDENID AS ID,
vorname AS Vorname,
nachname AS Nachname,
CONCAT(IFNULL(ROUND(SUM(Betrag), 2), 0), LPAD('Euro', 4, ' ')) AS Gesamt
FROM kunde k
LEFT JOIN verkauf v ON k.KUNDENID = v.KUNDENID
GROUP BY k.KUNDENID;
输出:
+----+---------+-----------+-------------+
| ID | Vorname | Nachname | Gesamt |
+----+---------+-----------+-------------+
| 1 | Homer | Simpson | 20.95Euro |
| 2 | Doug | Heffernan | 120.50Euro |
| 3 | Dexter | Morgan | 350.30Euro |
| 4 | Sheldon | Cooper | 1500.00Euro |
| 5 | Maurice | Moss | 0.00Euro |
+----+---------+-----------+-------------+
所以我想要的输出如下:
+----+---------+-----------+--------------+
| ID | Vorname | Nachname | Gesamt |
+----+---------+-----------+--------------+
| 1 | Homer | Simpson | 20.95 Euro |
| 2 | Doug | Heffernan | 120.50 Euro |
| 3 | Dexter | Morgan | 350.30 Euro |
| 4 | Sheldon | Cooper | 1500.00 Euro |
| 5 | Maurice | Moss | 0.00 Euro |
+----+---------+-----------+--------------+
如何正确对齐?
感谢您的帮助!
答案 0 :(得分:3)
通过连接'<space>Euro'
而不是LPAD('Euro',4,' ')
来简化concat,并在整个concat中添加一个LPAD以使其向右移动(您可以根据您的数据决定需要多少个字符才能对齐):
SELECT k.KUNDENID AS ID,
vorname AS Vorname,
nachname AS Nachname,
LPAD(
CONCAT(IFNULL(ROUND(SUM(Betrag), 2), 0), ' Euro')
, 13, ' ') AS Gesamt
FROM kunde k
LEFT JOIN verkauf v ON k.KUNDENID = v.KUNDENID
GROUP BY k.KUNDENID;
答案 1 :(得分:1)
移动LPAD()
,您需要它来处理整个结果,而不仅仅是Euro
:
SELECT
k.KUNDENID AS ID,
vorname AS Vorname,
nachname AS Nachname,
LPAD(CONCAT(IFNULL(ROUND(SUM(Betrag), 2), 0), ' Euro'), 15) AS Gesamt
FROM kunde k
LEFT JOIN verkauf v ON k.KUNDENID = v.KUNDENID
GROUP BY k.KUNDENID;
<强>结果:强>
+----+---------+-----------+-----------------+
| ID | Vorname | Nachname | Gesamt |
+----+---------+-----------+-----------------+
| 1 | Homer | Simpson | 20.95 Euro |
| 2 | Doug | Heffernan | 120.50 Euro |
| 3 | Dexter | Morgan | 350.30 Euro |
| 4 | Sheldon | Cooper | 1500.00 Euro |
| 5 | Maurice | Moss | 0.00 Euro |
+----+---------+-----------+-----------------+
答案 2 :(得分:0)
为什么不使用asterisk (*)
而不是空格,因为mySQL看起来是忽略LPAD()
函数中的空格。
SELECT k.KUNDENID AS ID,
vorname AS Vorname,
nachname AS Nachname,
CONCAT(LPAD(IFNULL(ROUND(SUM(Betrag), 2), 0),15,'*', ' Euro') AS Gesamt
FROM kunde k
LEFT JOIN verkauf v ON k.KUNDENID = v.KUNDENID
GROUP BY k.KUNDENID;
查看我的 SqlFiddle Demo