如何从数字中缩写?

时间:2016-07-10 16:22:48

标签: mysql sql

这是我目前的表格:

// table
+----+--------+------------+
| id |  name  | reputation |
+----+--------+------------+
| 1  | jack   | 534431     |
| 2  | peter  | 334        |
| 3  | amos   | 1300       |
| 4  | carter | 13490      |
| 5  | basil  | 1351       |
+----+--------+------------+

我想将reputation列的值更改为基于千克的数字。实际上我正试图缩短它。完全是stackoverflow的作用。所以预期的输出是这样的:

// newtable
+----+--------+------------+
| id |  name  | reputation |
+----+--------+------------+
| 1  | jack   | 534k       |
| 2  | peter  | 334        |
| 3  | amos   | 1.3k       |
| 4  | carter | 13.4k      |
| 5  | basil  | 1.3k       |
+----+--------+------------+

我该怎么做?

2 个答案:

答案 0 :(得分:2)

我可以像这样使用CASE WHENTRAILING

SELECT id, name,
    CASE WHEN value >= 1000 THEN
         CONCAT(TRIM(TRAILING '.' FROM SUBSTR(TRUNCATE(number/1000, 1), 1, 4)), 'k')
         ELSE value
    END as reputation
FROM `table`

答案 1 :(得分:1)

您可以使用concat()case和一些算术:

select id, name,
       (case when reputation < 1000 then cast(reputation as char)
             when reputation < 1000000 then concat(cast(floor(reputation/1000) as char), 'k')
             when reputation < 1000000000 then concat(cast(floor(reputation/1000000) as char), 'M')
             else 'Wow!!!'
        end) as reputation
. . .

编辑:

获取某些值的小数点:

select id, name,
       (case when reputation < 1000 then format(reputation, 0)
             when reputation < 100000 then concat(format(reputation/1000, 2), 'k')
             when reputation < 1000000 then concat(format(reputation/1000, 0), 'k')
             when reputation < 100000000 then concat(format(reputation/1000000, 1), 'M')
             when reputation < 1000000000 then concat(format(reputation/1000000, 0), 'M')
             else 'Wow!!!'
        end) as reputation
. . .

Here是一个SQL小提琴。