如何在一列中使用SUM从数据库中检索数据的值

时间:2018-09-26 10:23:36

标签: mysql json database codeigniter

我有一个函数以json的形式从数据库中检索值。我需要从数据库中获取一些数据以及某些列的SUM值。当我不从那些值中检索SUM时,我会获得所有必需的数据,但是当我还包含SUM函数要从某些列中获取总值,我只会得到单个值对象

模型

    public function search_tickets($data){
    $ticketDate = $data['ticket_date'];
    $ticketBus = $data['ticket_bus'];
    $ticketAgentId = $data['agent_id'];
        $user = $this->db->select("
        CONCAT_WS(' ', tp.firstname, tp.lastname) AS passenger_name,
        tb.seat_numbers AS seat_number,
        tb.id_no AS ticket_number,
        fr.reg_no AS bus_number,
        DATE_FORMAT(ta.start_date, '%d/%m/%Y') as ticket_date,
        tb.price AS fare_paid,
                tb.pickup_trip_location AS boarding,
                tb.drop_trip_location AS dropping,
                    SUM(tb.price) AS total_fare
            ")
        ->from('tkt_booking AS tb')
        ->join('tkt_passenger AS tp', 'tb.tkt_passenger_id_no = tp.id_no' ,'full')
        ->join('trip_assign AS ta', 'ta.id = tb.trip_id_no' ,'full')
        ->join('trip_route AS tr', 'tr.id = tb.trip_route_id','full')
        ->join('agent AS a', 'a.agent_id = tb.agent_id','full')
        ->join('fleet_registration AS fr', 'fr.id = ta.fleet_registration_id','full')
        ->where('ta.start_date', $ticketDate )
        ->where('fr.reg_no', $ticketBus )
        ->where('tb.agent_id', $ticketAgentId )
        ->get()
        ->result();
    return $user;
}

控制器

    public function searchTickets(){ 
                $data = $_POST; 
        $ticket=$this->booking_model->search_tickets($data);
        if($ticket){
            $result =  array('tickets'=>$ticket);
        } else {
            $result =  NULL;
        }
        print json_encode($result);
 } 

1 个答案:

答案 0 :(得分:0)

您应该{}乘客ID以获取每位乘客的总和:

GROUP BY