CodeIgniter Forums
Combining multiple queries to get the result - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: Combining multiple queries to get the result (/showthread.php?tid=91794)



Combining multiple queries to get the result - marciakinnon - 10-13-2024

Hi,
I want to do some calculations but no success , how to convert this in simple and working query, most important variable is $sale_cost. What I would like to achieve is $sale_cost, I am also selecting $sale_cost in another query

Is there any shortcut to do all calculation in few working queries

Any help is very appreciated


RE: Combining multiple queries to get the result - evelynwang - 05-26-2025

To streamline your workflow, consider using a CTE (Common Table Expression) or a temporary table to calculate sale_cost once and reuse it across multiple queries. For example:
Code:
WITH sales_calculation AS (
    SELECT
        product_id,
        (price * quantity - discount) AS sale_cost  -- Your formula here
    FROM orders
)
-- Query 1: Get sale_cost for specific products
SELECT sale_cost FROM sales_calculation WHERE product_id = 123;
-- Query 2: Aggregate sale_cost (e.g., average)
SELECT AVG(sale_cost) FROM sales_calculation;