Substraction in MYSQL with some condition - mysql

I want to do SUM and SUBTRACTION upon certain condition within mysql query
i have try like this,
asuming the $balance= 655.000.000 then total amount inside my_table = IDR 80.000.000 and USD 500.000
$currency_id = 1;
$balance = 655.000.000;
DB::table('my_table as a')
->join('master_currencies as b', 'a.master_currency_id', 'b.id')
->where('a.id', $id)
->selectRaw("SUM(
CASE
WHEN $currency_id = a.master_currency_id THEN $balance - a.amount
ELSE
a.amount
END) AS net_value, b.symbol, b.id as master_currency_id"
)
->groupBy('b.id')
->get();
The code above should give the result
[
{"net_value":"575.000.000","symbol":"IDR","master_currency_id":1},
{"net_value":"500.000","symbol":"USD","master_currency_id":2}
]
but the result i got is
[
{"net_value":"1.885.000.000","symbol":"IDR","master_currency_id":1},
{"net_value":"500.000","symbol":"USD","master_currency_id":2}
]
Note:
Please ignore dots between numbers, in my database i'm not using these dots. it is for inquiry purposes only

If you have more than one row of IDR then it might be a problem with order of operations.
For example say you have to values (100.000.000) and (50.000.000) then for IDR SUM(655.000.000-100.000.000, 655.000.000-50.000.000)=1.160.000.000 and is not the same as 655.000.000-SUM(100.000.000,50.000.000)=505.000.000 the problem being that each row in the group that you aggregate gets a clean $balance.
You could potentially solve this by doing:
$currency_id = 1;
$balance = 655.000.000;
DB::table('my_table as a')
->join('master_currencies as b', 'a.master_currency_id', 'b.id')
->where('a.id', $id)
->selectRaw("
(CASE
WHEN a.id=$currency_id $balance-SUM(a.amount)
ELSE
SUM(a.amount)
END) AS net_value, b.symbol, b.id as master_currency_id")
->groupBy('b.id')
->get();

Related

How to calculate subtraction of 2 Sql Query

I want to do a subtraction operator between entotalitem and extotalitem.query that I use retrieve data from the same table that is tbl_orders_data.
I have tried by creating 2 queries, the first is the query to retrieve entotalitem and the second query to retrieve extotalitem
$encheck = DB::table('tbl_orders_data')
->select('slot_id', DB::raw('sum(total_item) as entotalitem'))
->where('id_order_data', 'like', 'PBM' . '%')
->groupBy('slot_id')
->pluck('entotalitem');
$excheck = DB::table('tbl_orders_data')
->select('slot_id', DB::raw('sum(total_item) as extotalitem'))
->where('id_order_data', 'like', 'PBK' . '%')
->groupBy('slot_id')
->pluck('extotalitem');
$en = $encheck;
$ex = $excheck;
dd($en - $ex);
Should I only need to use one query? or should I make 2 queries as I have tried?
please help me, thanks
You may use conditional aggregation here:
$check = DB::table('tbl_orders_data')
->select('slot_id', DB::raw("sum(case when id_order_data like 'PBM%' then total_item else 0 end) -
sum(case when id_order_data like 'PBK%' then total_item else 0 end) as totalitem"))
->groupBy('slot_id')
->pluck('totalitem');

Codeigniter's Model with QueryBuilder JOIN query

Really new to working with CI4's Model and struggling to adapt my existing MySQL JOIN queries to work with the examples in its User Guide.
I have adapted part of my code like so:
public function brand_name($brand_name_slug)
{
return $this->asArray()
->where('availability', 'in stock')
->where('sku !=', '')
->where('brand_name_slug', $brand_name_slug)
->groupBy('gtin')
->orderBy('brand_name, subbrand_name, product, size, unit')
->findAll();
}
It works fine. I have looked at examples, and figured out I can add the code ->table('shop a') and it still works, but I also need to to add the following JOIN statement:
JOIN (SELECT gtin, MIN(sale_price) AS sale_price FROM shop GROUP BY gtin) AS b ON a.gtin = b.gtin AND a.sale_price = b.sale_price
As soon as I add ->join('shop b', 'a.gtin = b.gtin and a.sale_price = b.sale_price') I get a '404 - File Not Found' error.
When I look at all examples of CI4 joins and adapt my code to fit, my foreach($shop as $row) loop generates a 'Whoops...' error because they end with a getResult() or getResultArray - instead of findAll().
Which is the way forward, and do I need to change my foreach loop.
Full MySQL statement:
SELECT * FROM shop a JOIN (SELECT gtin, MIN(sale_price) AS sale_price FROM shop GROUP BY gtin) AS b ON a.gtin = b.gtin AND a.sale_price = b.sale_price WHERE availability = 'in stock' AND sku != '' AND brand_name_slug = $brand_name_slug GROUP BY gtin ORDER BY brand_name, subbrand_name, product, size
Query builders have their limits. That's why the query method exists. If you have a complex query I'd advise you to just use $this->query();.
It will make you lose less time and effort converting something you know already works. And in the top of that, while converting complex queries you usually end up using the query builder but with big part of your SQL in it.
In your model extending CodeIgniter\Model :
$query = $this->db->query("SELECT * FROM shop a JOIN (SELECT gtin, MIN(sale_price) AS sale_price FROM shop GROUP BY gtin) AS b ON a.gtin = b.gtin AND a.sale_price = b.sale_price WHERE availability = 'in stock' AND sku != '' AND brand_name_slug = \$brand_name_slug GROUP BY gtin ORDER BY brand_name, subbrand_name, product, size");
// your array result
$result_array = $query->getResultArray();
// your object result
$result_object = $query->getResult();
BaseBuilder Class in Codeigniter expects the first join parameter to be the table name. So try passing the table name and join it on the table name itself. I haven't personally used the table aliases so I might also be wrong.
Following are the parameter that the JOIN query expects :
public function join(string $table, string $cond, string $type = '', bool $escape = null)
Here, it expects the first name be a table, so try out by switching aliases for the table's name directly.
For your second part of query, It would be better if you could show the whole error rather than just posting the first of the error.
Managed to figure it out in the end:
public function brand_name($brand_name_slug)
{
return $this
->db
->table('shop a')
->select()
->join('(SELECT sku, MIN(sale_price) AS sale_price FROM shop GROUP BY sku) AS b', 'a.sku = b.sku AND a.sale_price = b.sale_price')
->where('availability', 'in stock')
->where('a.sku !=', '')
->where('brand_name_slug', $brand_name_slug)
->groupBy('a.sku')
->orderBy('brand_name, subbrand_name, product, size, unit')
->get()
->getResult();
}
Thanks for all your pointers!

Trouble interpreting what is making my query so slow

I have a query that takes 15 seconds to get 350 results in a MySQL 5.6 Server and I am unable to diagnose why, I am still very new to database optimizing. U
The EXPLAIN visual does show some non-unique key lookups but each only says one 1 row look up.
The tabular EXPLAIN which I am not able to interpret and I am hoping someone else can here looks like .
I have tried switching the ending LIMIT = 350 to 100, 10, and the query takes exactly the same amount of time to run, about 15 seconds.
I have tried nixing the views but besides making it hard to recreate this query it did not improve performance.
Perhaps related, in other EXPLAIN statements in our MySQL DB, I've seen a view referenced with Materialized next to it, but that does not appear near next to any of the three views used in this query, in fact I don't even see the views referenced at all instead only the tables they reference. Is that a factor?
My last attempt was replacing the final selected column which is a listlineitems.* with the specific columns, since I've read that can improve speed and is just better practice, but I get the sense that is not going to dramatically improve this situation.
Here's the query -
SELECT
0 AS 'Check',
DATE_FORMAT(`listlineitems`.`dateEntered`,
'%Y-%m-%d') AS 'Date Entered',
`listlineitems`.`itemId` AS 'parentTableIdx',
`listlineitems`.`parentProjectId` AS 'parentProjectIdx',
`listlineitems`.`idx` AS 'ID',
IF(`listlineitems`.`active` = 1,
'Active',
'Inactive') AS 'Active/Inactive',
CONCAT(`listUsers`.`FirstName`,
' ',
`listUsers`.`LastName`) AS 'Employee',
CASE `listlineitems`.`type`
WHEN 1 THEN 'Time Entry'
WHEN 2 THEN 'Expense Entry'
END AS 'Type',
`listcustomers`.`name` AS 'Customer',
`listlocations`.`name` AS 'Location',
`listareas`.`name` AS 'Area',
`listassets`.`name` AS 'Asset',
`listprojects`.`name` AS 'Project',
`listprojects`.`number` 'Project #',
`listprojects`.`autoassign` 'autoassign',
`listactivities`.`name` AS 'Activity',
(CASE `listlineitems`.`type`
WHEN 1 THEN `listlineitems`.`qty`
WHEN 2 THEN `listlineitems`.`qty`
END) AS 'Quantity',
`listlineitems`.`taxable` AS 'Taxable',
`listlineitems`.`totalAmount` - `listlineitems`.`taxAmount` AS 'Pre-Tax Amount',
`listlineitems`.`taxAmount` AS 'Tax Amount',
`listlineitems`.`totalAmount` AS 'Total Amount',
`listCustomers`.`idx` AS 'parentCustomerIdx',
`listLocations`.`idx` AS 'parentLocationIdx',
`listAreas`.`idx` AS 'parentAreaIdx',
`listAssets`.`idx` AS 'parentAssetIdx',
CONCAT(`listcustomers`.`name`,
'/',
`listlocations`.`name`,
'/',
`listareas`.`name`,
'/',
`listassets`.`name`,
'/',
`listprojects`.`name`) AS 'Path',
IF(`listlineitems`.`customerViewable` = 1,
'Yes',
'No') AS 'Cust. Viewable',
(CASE
WHEN `listlineitems`.`type` = 2 THEN `listexpenseentry`.`TotalCostToPSI` - `listexpenseentry`.`TaxCostToPSI`
ELSE `listlineitems`.`totalAmount` - `listlineitems`.`taxAmount`
END) AS 'preTaxCostPSI',
(CASE
WHEN `listlineitems`.`type` = 2 THEN `listexpenseentry`.`TaxCostToPSI`
ELSE `listlineitems`.`taxAmount`
END) AS 'taxCostPSI',
(CASE
WHEN `listlineitems`.`type` = 2 THEN `listexpenseentry`.`TotalCostToPSI`
ELSE `listlineitems`.`totalAmount`
END) AS 'totalCostPSI',
view_solinx2.lastAltered AS 'lastalteredSO',
view_polinx2.lastAlteredPO AS 'lastalteredPO',
view_invlinx2.lastAlteredInv AS 'lastalteredInv',
view_solinx2.lastAlteredAfterConfirmation AS 'lastAlteredAfterConfirmation',
view_solinx2.roleIdSO AS 'roleIdSO',
view_polinx2.roleIdPO AS 'roleIdPO',
view_polinx2.userIdPO AS 'userIdPO',
view_polinx2.lastAlteredafterConfirmation AS 'lastAlteredAfterConfirmationPO',
view_invlinx2.roleIdInv AS 'roleIdInv',
view_invlinx2.userIdInv AS 'userIdInv',
view_invlinx2.lastAlteredafterConfirmation AS 'lastAlteredAfterConfirmationInv',
view_solinx2.roleId AS 'roleId',
view_solinx2.userId AS 'userId',
view_solinx2.soId AS 'SOId',
view_solinx2.autoassignSO AS 'autoassignSO',
IF(view_solinx2.notNeeded = 1,
'Not Needed',
view_solinx2.number) AS 'SOname',
view_solinx2.dateEntered AS 'SoDate',
view_solinx2.totalSOAmount AS 'SoTotal',
view_invlinx2.invId AS 'InvId',
IF(view_solinx2.notNeeded = 1,
'------',
view_invlinx2.`number`) AS 'InvName',
view_invlinx2.dateEntered AS 'InvDate',
view_invlinx2.amount AS 'InvTotal',
view_polinx2.poId AS 'POId',
IF(view_solinx2.notNeeded = 1,
'------',
view_polinx2.`number`) AS 'POName',
view_polinx2.dateEntered AS 'PODate',
view_polinx2.amount AS 'POTotal',
(SELECT
listsalesorders.number
FROM
listsalesorders
WHERE
listsalesorders.idx = autoassign) AS 'test',
`listlineitems`.*
FROM
`listlineitems`
LEFT JOIN
`listUsers` ON `listlineitems`.`individualId` = `listUsers`.`idx`
LEFT JOIN
`listprojects` ON `listlineitems`.`parentProjectId` = `listprojects`.`idx`
LEFT JOIN
`listassets` ON `listlineitems`.`parentAssetId` = `listassets`.`idx`
LEFT JOIN
`listareas` ON `listlineitems`.`parentAreaId` = `listareas`.`idx`
LEFT JOIN
`listlocations` ON `listlineitems`.`parentLocationId` = `listlocations`.`idx`
LEFT JOIN
`listcustomers` ON `listlineitems`.`parentCustomerId` = `listcustomers`.`idx`
LEFT JOIN
`listactivities` ON `listactivities`.`idx` = `listlineitems`.`activityCode`
LEFT JOIN
`listexpenseentry` ON (`listexpenseentry`.`idx` = `listlineitems`.`itemId`
AND `listlineitems`.`type` = 2)
LEFT JOIN
view_solinx2 ON view_solinx2.idx = listlineitems.idx
LEFT JOIN
view_polinx2 ON view_polinx2.idx = listlineitems.idx
LEFT JOIN
view_invlinx2 ON view_invlinx2.idx = listlineitems.idx
GROUP BY `listlineitems`.`idx`
ORDER BY `listlineitems`.`dateEntered` DESC
LIMIT 10;
I am at a loss as to what else I can do to improve this and any suggestions are very much appreciated.
You are selecting everything from listlineitems table (100+ K records), joining many tables, then grouping by idx and then throwing out most results.
You can:
Try to add unique index (dateEntered, idx) to listlineitems
Try limit listlineitems by dateEntered if acceptable (WHERE dateEntered > DATE_SUB(NOW(), INTERVAL 30 DAYS)). dateEntered must be indexed
Try to put select from listlineitems + grouping + limit into subquery so MySQL will do joins to only these 10 rows returned by subquery.
Convert dependent subquery (listsalesorders) to left join

Codeigniter join, group by and count a row from one table

I'm struggling a bit with this code to get the count result from book_listing (totally) which is the total count of bookings. From the result, some are correct but some are multiplied by 3 or so.
Here is my code:
$this->db->where('list_status', 1)
->where('list_date >=', date('Y-m-d'))
->order_by("user_listings.list_created", "desc")
->limit(18, null)
->select('*, COUNT(user_bookings.book_listing) as totally')
->from('user_listings')
->join('user_images', 'user_images.img_listing = user_listings.list_reference')
->join('user_states', 'user_states.state_id = user_listings.list_state')
->join('user_bookings', 'user_bookings.book_listing = user_listings.list_reference', 'left')
->group_by('user_listings.list_reference')
->get();
Thanks to any help :)
So I solved it, the user_images table seems to be causing the issue due to multiple images being fetched while I need it to return only one.
$this->db->where('list_status', 1)
->where('list_date >=', date('Y-m-d'))
->order_by("user_listings.list_created", "desc")
->limit(18, null)
->select('user_listings.*,image.*,user_states.*')
->select('COUNT(user_bookings.book_listing) as totalBooked')
->from('user_listings')
->join('user_bookings', 'user_bookings.book_listing = user_listings.list_reference', 'left')
->join('(SELECT * FROM user_images WHERE user_images.img_key IN(SELECT MIN(user_images.img_key) FROM user_images GROUP BY user_images.img_listing)) AS image',
'image.img_listing = user_listings.list_reference')
->join('user_states', 'user_states.state_id = user_listings.list_state')
->group_by('user_listings.list_reference')
->get();
Basically, I had to do a select from the join table for user_images. Hope it helps someone else :)

How to specify an array in the Where clause using Moodle DB API Call?

I want to filter data based on an array, similar to "in" keyword in a query:
SELECT count(*) as number_of_records,
count(CASE WHEN result = 'SUCCESS' THEN 1 END) as successful_builds_no,
min(CASE WHEN result = 'FAILURE' THEN 0 ELSE 1 END) as is_success,
min(duration) as best_duration,
max(build_date) as build_date
FROM mdl_selenium_results
WHERE build_date in ('2014-03-13', '2014-03-12')
GROUP BY build_date
How to achieve that using Moodle DB api??
If you are creating an SQL query to use within Moodle, you could just use the IN keyword, exactly as you have done in the example.
Alternatively, to make it a bit more cross-DB compatible, and to make your queries run a bit faster when there is only one item in the list, you can write:
list($dsql, $dparam) = $DB->get_in_or_equal(array('2014-03-13', '2014-03-12'), SQL_PARAMS_NAMED);
$sql = "SELECT count(*) as number_of_records,
count(CASE WHEN result = 'SUCCESS' THEN 1 END) as successful_builds_no,
min(CASE WHEN result = 'FAILURE' THEN 0 ELSE 1 END) as is_success,
min(duration) as best_duration,
max(build_date) as build_date
FROM {selenium_results}
WHERE build_date $dsql
GROUP BY build_date";
$result = $DB->get_records_sql($sql, $dparams);
OR, if you just want to get all the matching records from the given table (and then worry about doing the calculations in PHP), you could write:
$result = $DB->get_records_list('selenium_results', 'build_date', array('2014-03-13', '2014-03-12'));
(I've not run any of the code above, so apologies for any typos)