2
+-----+-----+-------+
| PID | Qty | Price |
+-----+-----+-------+
|   1 |   5 |   100 |
|   2 |  10 |   500 |
|   3 |   4 |   300 |
+-----+-----+-------+

$this->db->select("SUM(qty) as total, price as last price");
$this->db->from('table');
$query = $this->db->get();
$result = $query->result();

Now the above code will return as many rows as there is price,

I want to return only one row where there is total of qty and the last value of price

Expected output:

Array (
    [0] => stdClass Object
        (
            [total] => 19
            [last_price] => 300
        )
)

I have a table with thousands of rows of qty and price, but I want to select the total sum of column qty and only the last value of the price, not sum of qty and all rows of price, I want only the last value of price how do I write my select query ?

Thank you in advance.

5
  • How do you define about the last row? Commented Apr 24, 2017 at 9:29
  • $this->db->select("SUM(qty) as total, price as last price ORDER BY PID DESC limit 1"); Commented Apr 24, 2017 at 9:30
  • @AlivetoDie the above doesn't work.. Commented Apr 24, 2017 at 9:33
  • @AlivetoDie yup it doesn't work Commented Apr 24, 2017 at 9:34
  • @Forward the last row is the last value of column price Commented Apr 24, 2017 at 9:34

3 Answers 3

2

You can do it like below:-

$this->db->select("SUM( qty ) AS qty, (SELECT Price FROM  <table name> ORDER BY PID DESC LIMIT 1) AS Price");
$this->db->from('table');

Note:- Instead of <table name> write your actual table name there. Also take care of column-names as well.

Sign up to request clarification or add additional context in comments.

2 Comments

Nice, thank you, didn't know you can put another SELECT inside the select statement. Thanks!
@Charas glad to help you.:):)
1

Try this:

SELECT SUM(qty), a.*
FROM products, 
(SELECT price FROM products
ORDER BY pid DESC 
LIMIT 1) a;

Comments

1

you can get result using this

SELECT SUM(qty) As qty, (SELECT Price FROM table price desc limit 1) AS price FROM table price dlimit 1

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.