我正在尝试将10月份的第10列中的所有值相加,但我似乎有unix时间戳
我尝试了以下但是值仍为0
<?php
echo $this->db->select('(SELECT SUM(amount_paid) FROM invoice WHERE MONTH ( `creation_timestamp` ) = 10) AS invoice');
$query = $this->db->get('invoice');
?>
...
CREATE TABLE `invoice`(
`invoice_id` int(11) NOT NULL AUTO_INCREMENT,
`student_id` int(11) NOT NULL,
`title` longtext COLLATE utf8_unicode_ci NOT NULL,
`description` longtext COLLATE utf8_unicode_ci NOT NULL,
`amount` int(11) NOT NULL,
`amount_paid` longtext COLLATE utf8_unicode_ci NOT NULL,
`due` longtext COLLATE utf8_unicode_ci NOT NULL,
`creation_timestamp` int(11) NOT NULL,
`payment_timestamp` longtext COLLATE utf8_unicode_ci NOT NULL,
`payment_method` longtext COLLATE utf8_unicode_ci NOT NULL,
`payment_details` longtext COLLATE utf8_unicode_ci NOT NULL,
`status` longtext COLLATE utf8_unicode_ci NOT NULL COMMENT 'paid or unpaid',
PRIMARY KEY (`invoice_id`)
) ENGINE=MyISAM AUTO_INCREMENT=73 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
答案 0 :(得分:1)
我们正在寻找2015年10月的总和(我认为)
SELECT UNIX_TIMESTAMP('2015-10-01'); -- '1443672000'
SELECT UNIX_TIMESTAMP('2015-10-31 23:59:59'); -- 1446350399
SELECT UNIX_TIMESTAMP('2015-11-01'); -- '1446350400'
请注意以上值
drop table invoice2;
create table invoice2
( id int auto_increment primary key,
amount decimal(12,2) not null,
ts int(11) not null -- from unix timestamp
);
-- truncate table invoice2;
insert invoice2(amount,ts) values
(10,unix_timestamp('2015-10-01')),
(10,unix_timestamp('2015-10-01')),
(3310,unix_timestamp('2015-11-01')),
(3310,unix_timestamp('2015-11-01')),
(44410,unix_timestamp('2016-01-01')),
(5510,unix_timestamp('2016-02-01')),
(6610,unix_timestamp('2016-02-01'));
所以你想要2015年10月份的以下风味的东西:
select sum(amount) as theSum
from invoice2
where month(from_unixtime(ts))=10
and year(from_unixtime(ts))=2015;
+--------+
| theSum |
+--------+
| 20.00 |
+--------+
感兴趣的功能是 get_sum()
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class department_model extends CI_Model{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
//read the department list from db
function get_department_list()
{
$sql = 'select var_dept_name, var_emp_name from tbl_dept, tbl_emp where tbl_dept.int_hod = tbl_emp.int_id';
$query = $this->db->query($sql);
$result = $query->result();
return $result;
}
// get the sum of amount based on parameters month and year passed
function get_sum($month,$year)
{ $myQuery="select sum(amount) as theSum from invoice2 where month(from_unixtime(ts))=$month
and year(from_unixtime(ts))=$year";
$query = $this->db->query($myQuery);
$result = $query->result();
return $result;
}
}
答案 1 :(得分:0)
您的查询和代码也存在一些问题。当您直接在数据库上执行查询时,它会给出错误。此外,对于自定义查询,我们必须在CI中使用$this->db->query()
函数。以下是正确的查询代码段。
<?php
echo $this->db
->query('SELECT SUM(amount_paid) AS invoice FROM invoice WHERE MONTH ( `creation_timestamp` ) = 10 ')
->row()->invoice;
?>