用Go、sqlx、ClickHouse扫描Decimal类型的sum()
我在 ClickHouse 表中有一个 Decimal(38, 3) 类型的“持续时间”字段。
我从我的 Golang 服务发送一个查询来获取它的 SUM() 但我无法扫描回结果。我尝试使用 int、uint、float、sql.NullFloat64、结构类型、逐行扫描、整个结构、数组、带数组的结构、使用 sqlx.Query、sqlx.Select 但没有任何效果。
rows, _ := s.db.Query("SELECT sum(Duration) AS duration FROM mytable")
for rows.Next() {
var count sql.NullFloat64
log.Println(rows.Scan(&count))
log.Printf("count: %v\n", count)
}
我总是收到此类错误: sql:列索引 0 上扫描错误,名称“持续时间”:转换驱动程序。值类型 []uint8 (“\x04!\xdf\xdc\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00") 到 float64:无效语法
在检查一些行信息时,我得到以下信息
log.Printf("db type name: %v\n", t.DatabaseTypeName())
log.Printf("db scan type: %v\n", t.ScanType())
>>>
db type name: Decimal(38, 3)
db scan type: []uint8
:其他不带聚合函数的 Decimal 类型的 SELECT 语句我使用了 float32/64,但这个不起作用。
直接在控制台中运行查询,我得到了预期的单个值:3702.5
有什么想法吗?
--- 更新 1 ---
我设法将其扫描为字节数组,但我不知道如何将其转换为客户端中显示的数字:3708199.5
count := []byte{}
rows.Scan(&count)
log.Printf("count: %v\n", count)
>>>
count: [76 162 6 221 0 0 0 0 0 0 0 0 0 0 0 0]
I have a "Duration" field of type Decimal(38, 3) in a ClickHouse table.
From my Golang service I'm sending a query to get the SUM() of it but I just can't scan the result back. I tried using int, uint, float, sql.NullFloat64, a struct type, scanning row by row, the whole struct, arrays, structs with arrays, using sqlx.Query, sqlx.Select and nothing worked.
rows, _ := s.db.Query("SELECT sum(Duration) AS duration FROM mytable")
for rows.Next() {
var count sql.NullFloat64
log.Println(rows.Scan(&count))
log.Printf("count: %v\n", count)
}
I always get back this kind of errors:sql: Scan error on column index 0, name "duration": converting driver.Value type []uint8 ("\x04!\xdf\xdc\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00") to a float64: invalid syntax
While checking some of the rows info I get the following:
log.Printf("db type name: %v\n", t.DatabaseTypeName())
log.Printf("db scan type: %v\n", t.ScanType())
>>>
db type name: Decimal(38, 3)
db scan type: []uint8
For other SELECT statements of Decimal types without aggregation functions I used float32/64 but this one just refuses to work.
Running the query directly in the console I get a single value as expected: 3702.5
Any ideas?
--- UPDATE 1 ---
I manage to scan it into a byte array but I don't know how to transform it into the number shown in the client: 3708199.5
count := []byte{}
rows.Scan(&count)
log.Printf("count: %v\n", count)
>>>
count: [76 162 6 221 0 0 0 0 0 0 0 0 0 0 0 0]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从库的 v1 迁移到 v2 后,sum() 现在返回一个字符串,但它仍然失败,因为目标是浮点数,因此我将值转换为已知类型来修复它。
After migration from v1 to v2 of the library, the
sum()
returns now an string, but it still fails because the destination is a float, so I cast the value to a known type to fix it.