开发者

Find the sum of product cost from items sold

I have a CodeIgniter website and i'm building some stats for the retailer. I need to find the sum of product_cost for all products sold, where the produc开发者_如何转开发t 'category1' is equal to 1.

The data structure below shows 'products' and 'order_items', which as the name suggests contains all the items sold.

products
---
product_id
category1
product_price
product_cost

order_items
---
order_id
product_id
quantity

So basically I am trying to get the correct SQL statement in CodeIgniter to form a function in my orders_model.

Grateful for any help. :)


Assuming you are not using Active Record and just want a simple query, this should give you the result you need:

SELECT SUM(product_cost) AS total_cost FROM products RIGHT JOIN order_items ON products.product_id = order_items.product_id WHERE products.category1 = 1

Active Record will look something like this:

$this->db->select('SUM(product_cost) AS total_cost');
$this->db->from('products');
$this->db->join('order_items', 'products.product_id = order_items.product_id', 'right');
$this->db->where('products.category1',1);
$query = $this->db->get();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜