Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have hypothetical table (for the convenience of the indices used real names)
table: product_price
id: | product | valuta | location | price
------------------------------------------------------------------
01 | milk | EUR | London | 20
02 | milk | USD | Boston | 19
03 | milk | JPY | Boston | 180
04 | apple | USD | Boston | 200
05 | apple | USD | Springfild | 210

how get this array?

array(<br>
 array('id'=>01, 'product'=>milk,  'location'=>'Boston', 'price_USD'=>19, 'price_JPY'=>180),<br>
 array('id'=>02, 'product'=>apple, 'location'=>'Boston', 'price_USD'=>200)<br>
);
share|improve this question
    
Why in array id for the first element is 1? In db it's 2. Or it's no longer an id but rather just a sequential number? –  peterm Jun 29 '13 at 19:23

1 Answer 1

up vote 0 down vote accepted

Your base query might look like

SELECT MIN(id) id,
       MIN(location) location,
       product,
       MIN(CASE WHEN valuta = 'USD' THEN price END) price_usd,
       MIN(CASE WHEN valuta = 'JPY' THEN price END) price_jpy
  FROM product_price
 WHERE location = 'Boston'
 GROUP BY product
 ORDER BY id

Output:

| ID | LOCATION | PRODUCT | PRICE_USD | PRICE_JPY |
---------------------------------------------------
|  2 |   Boston |    milk |        19 |       180 |
|  4 |   Boston |   apple |       200 |    (null) |

Here is SQLFiddle demo

Now I'm not a codeigniter expert but in codeigniter it might look

$result = $this->db
               ->select(
                'MIN(id) id,
                 MIN(location) location,
                 product,
                 MIN(CASE WHEN valuta = 'USD' THEN price END) price_usd,
                 MIN(CASE WHEN valuta = 'JPY' THEN price END) price_jpy')
               ->from('product_price')
               ->where(array('location' => 'Boston')
               ->group_by(array('product')
               ->order_by(array('id')
               ->get();
share|improve this answer
    
Thank you! all works! –  VRetlev Jun 29 '13 at 20:31
    
You're welcome. Good luck :) –  peterm Jul 1 '13 at 2:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.