如何汇总varchar列?

时间:2015-05-15 12:13:58

标签: android sqlite

我尝试使用以下代码但显示无关值。 我注意到这是因为TX_AMOUNT的Varchar列。 如何更改代码以汇总该varchar列?

String[] columns = {VivzHelper.UID, helper.TX_NAME, 
"SUM("+helper.TX_AMOUNT+") AS "+helper.TX_AMOUNT, helper.TX_DATE };

Cursor c = db.query(VivzHelper.TX_TABLE, columns, helper.TX_ID + "='" + name 
+ "' AND " + helper.TX_DATE + " BETWEEN '" + datefrom.from_date + "' AND '"  
+ dateto.to_date + "  ' ",null,helper.TX_NAME, null, null);

1 个答案:

答案 0 :(得分:0)

使用CAST

SELECT CAST('1.11' as decimal)

来源:http://www.sqlite.org/lang_expr.html#castexpr

示例:

CREATE TABLE Test
    (`id` int, `productName` varchar(7), `amount` varchar(10))
;

INSERT INTO Test
    (`id`, `productName`, `amount`)
VALUES
    (1, 'Foo', '1.1'),
    (2, 'Bar', '1.1'),
    (3, 'Baz', '1.1')
;

SELECT
  SUM(CAST(amount as decimal))
FROM
  Test
 ;

关于你的案子:

String[] columns = {VivzHelper.UID, helper.TX_NAME, 
    "SUM(CAST("+helper.TX_AMOUNT+" as decimal)) AS "+helper.TX_AMOUNT, helper.TX_DATE };