php - Mysql查询SUM字段字符串和分组依据

标签 php mysql

我的塔尔贝名字是laporan, 当前查询是

"SELECT * FROM laporan"

然后如果我 print_r 我得到这样的结果数据:

[0] => Array
    (
        [tanggal_laporan] => 2012-11-04
        [total_kas] => Rp 21.000,-
    )

[1] => Array
    (
        [tanggal_laporan] => 2012-11-04
        [total_kas] => Rp 50.500,-
    )

[2] => Array
    (
        [tanggal_laporan] => 2012-11-04
        [total_kas] => Rp 56.000,-
    )

[3] => Array
    (
        [tanggal_laporan] => 2012-11-05
        [total_kas] => Rp 89.000,-
    )

[4] => Array
    (
        [tanggal_laporan] => 2012-11-05
        [total_kas] => Rp 73.000,-
    )

我想要对字段 total_kas 求和,该字段是 varchar/string,我的问题是有一种方法/可以对字段 varchar/string 求和。然后这个查询group_by tanggal_laporan,所以我想获取如下数据:

[0] => Array
    (
        [tanggal_laporan] => 2012-11-04
        [total_kas] => 127500
    )

[1] => Array
    (
        [tanggal_laporan] => 2012-11-05
        [total_kas] => 162000
    )

谢谢。

最佳答案

这应该有效(假设 total_kas 始终采用“Rp NUMBER,-”形式):

SELECT tanggal_laporan, SUM(CAST(
    SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(total_kas, '.', ''), ' ', -1), ',', 1)
    AS UNSIGNED INTEGER)) AS num 
FROM laporan 
GROUP BY tanggal_laporan

我做了一些更改来处理整数。这是SQLFiddle例子。 如果 UNSIGNED 不符合您的需求,请将其删除。

关于php - Mysql查询SUM字段字符串和分组依据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14153494/

相关文章:

php - 如何创建图像的显示顺序? (一道MySQL+PHP的问题)

php - 页面请求过多

php - token 在尝试刷新后被解除认证

mysql - 为什么这个外键约束不起作用?

mysql - 从多个嵌套子查询中进行选择的 SQL 查询

mysql - 从子查询返回多行?

php - 为什么 'Quantity' 值不显示任何值?

php - 如何避免 HTTP header 注入(inject)(换行字符)

php - __DIR__ VS 使用反射

mysql - sql日期如果不指定时间将默认引用00 :00:00 or 23:59:59