我将字节转换为人类可读格式。在结果的末尾,如果它是MB或KB或只是字节,则应该附加。我无法找到正确的方法。
Sqlite表内容。
+-----------+
| Data Sent |
+-----------+
| 17210032 |
+-----------+
| 60080929 |
+-----------+
| 64061961 |
+-----------+
| 29894 |
+-----------+
| 862 |
+-----------+
用于从字节转换为人类可读的Sqlite代码
select "Data Sent",
CASE
WHEN "Data Sent" > 1024*1024 then round("Data Sent"*1.0/(1024*1024), 2)
WHEN "Data Sent" > 1024 then round("Data Sent"*1.0/(1024), 2)
WHEN "Data Sent" < 1024 then "Data Sent"
ELSE NULL
end as conv_data
from testdb
第一个条件是从字节转换为兆字节。第二个是KB,最后一个是字节。
预期结果:
+-----------+-----------+
| Data Sent | conv_data |
+-----------+-----------+
| 17210032 | 16.41 MB |
+-----------+-----------+
| 60080929 | 57.3 MB |
+-----------+-----------+
| 64061961 | 61.09 MB |
+-----------+-----------+
| 29894 | 29.19 KB |
+-----------+-----------+
| 862 | 862 bytes |
+-----------+-----------+
但是当前代码只显示转换后的数字。我们如何在结果中附加MB,KB,字节?
答案 0 :(得分:1)
您可以使用SQLite Concatenation ||
,例如: -
SELECT "Data Sent",
CASE
WHEN "Data Sent" < 1024 THEN "Data Sent" || " Bytes."
WHEN "Data Sent" > 1024 AND "Data Sent" < 1048576 THEN round("Data Sent" * 1.0 / 1024,2) || " KB."
WHEN "Data Sent" > (1024 * 1024) THEN round("Data Sent" * 1.0/ (1024 * 1024),2) || " MB."
END AS conv_data
from testdb;
请注意!对于NULL检查,不需要ELSE子句,因为结果将为NULL。
结果: -