在Bigquery中:我们如何格式化一个数字,该数字将成为结果集的一部分,使其以逗号格式化:如1000000到1,000,000?
答案 0 :(得分:7)
下面的适用于标准SQL
SELECT
input,
FORMAT("%'d", input) as formatted
FROM (
SELECT 123 AS input UNION ALL
SELECT 1234 AS input UNION ALL
SELECT 12345 AS input UNION ALL
SELECT 123456 AS input UNION ALL
SELECT 1234567 AS input UNION ALL
SELECT 12345678 AS input UNION ALL
SELECT 123456789 AS input
)
适用于整数,但如果您还需要浮点数,则可以使用:
SELECT
input,
CONCAT(FORMAT("%'d", CAST(input AS int64)),
SUBSTR(FORMAT("%.2f", CAST(input AS float64)), -3)) as formatted
FROM (
SELECT 123 AS input UNION ALL
SELECT 1234 AS input UNION ALL
SELECT 12345 AS input UNION ALL
SELECT 123456.1 AS input UNION ALL
SELECT 1234567.12 AS input UNION ALL
SELECT 12345678.123 AS input UNION ALL
SELECT 123456789.1234 AS input
)
为Legacy SQL添加
顺便说一句,如果由于某种原因你被绑定到Legacy SQL - 下面是它的快速示例
SELECT input, formatted
FROM JS((
SELECT input
FROM
(SELECT 123 AS input ),
(SELECT 1234 AS input ),
(SELECT 12345 AS input ),
(SELECT 123456 AS input ),
(SELECT 1234567 AS input ),
(SELECT 12345678 AS input ),
(SELECT 123456789 AS input)
),
// input
input,
// output
"[
{name: 'input', type:'integer'},
{name: 'formatted', type:'string'}
]",
// function
"function (r, emit) {
emit({
input: r.input,
formatted: r.input.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
});
}"
)
以上示例使用Legacy SQL User-Defined Functions的内联版本,通常用于快速演示/示例 - 但不建议在制作中使用 - 如果您觉得它对您有用 - 您将需要"非常略"转换它 - 例如,见https://cloud.google.com/bigquery/user-defined-functions#webui
答案 1 :(得分:3)
使用标准SQL:
SELECT FORMAT("%'d", 1000123)
1,000,123
启用标准SQL的说明:https://cloud.google.com/bigquery/sql-reference/enabling-standard-sql
答案 2 :(得分:0)
改进米哈伊尔对浮动会议的回答 CAST(input AS int64) 将使像 12345.5 这样的数字在输出中变成 12346.50。 我将使用“.”分割。获取数字的整数部分,然后转换为 int64。
CREATE TEMP FUNCTION
format_n(x float64) AS (CONCAT(FORMAT("%'d", CAST(SPLIT(CAST(x AS string), '.')[
OFFSET
(0)] AS int64)),SUBSTR(FORMAT("%.2f", x), -3)));
SELECT
input,
format_n(input)
FROM (
SELECT
123 AS input
UNION ALL
SELECT
1234 AS input
UNION ALL
SELECT
12345 AS input
UNION ALL
SELECT
123456.8 AS input
UNION ALL
SELECT
1234567.12 AS input
UNION ALL
SELECT
12345678.127 AS input
UNION ALL
SELECT
123456789.1234 AS input )