`Convert mySQL Query to SQLite Using SUM and GROUP BY - mysql

I am working on a mobile app that is currently using an ajax call to run a mySQL query remotely and return the data as an array. I want to run the query locally using SQLite 3 an iPad. Below is the mySQL query. I am having trouble getting the query to work in SQLite
This is my working mySQL Query
SELECT
expense_date.expenseDate,
expenses.cost,
SUM(expenses.cost) as total,
expenses.name,
category.category
FROM expenses
INNER JOIN category ON expenses.catID = category.catID
INNER JOIN expense_date ON expenses.dateID = expense_date.dateID
WHERE expense_date.expenseDate BETWEEN '#from#' AND '#tu#'
AND expenses.catID != '1F27C7A1-3E16-5087-A313-A47D286A77A5'
AND expenses.catID != 'DF64C183-5056-A816-1ACA94F902242B61'
AND expenses.userID = '#userID#'
AND expenses.accountID = '#accountID#'
Group By expense_date.expenseDate
UPDATED MySQL Statement. This statement works in mySQL but not in SQLite 3.
SELECT
expense_date.expenseDate,
SUM(expenses.cost) as total
FROM expenses
INNER JOIN expense_date ON expenses.dateID = expense_date.dateID
WHERE expense_date.expenseDate
BETWEEN '2014-08-01' AND '2014-08-31'
AND expenses.catID != '1F27C7A1-3E16-5087-A313-A47D286A77A5'
AND expenses.catID != 'DF64C183-5056-A816-1ACA94F902242B61'
AND expenses.userID = 'C4C73329-5056-A816-1AB4B9FAE08FDB77'
AND expenses.accountID = '46298719-C78A-4CCE-8ADD-A3FD948DF93E'
Group By expense_date.expenseDate
This is the results of the query. 2014-08-21 has two values for that date: 2000.00 and 372.00 but they are added together and returned as a single value for 2014-08-21.
2014-08-01 32.00
2014-08-16 15.00
2014-08-19 513.55
2014-08-21 2372.00
2014-08-22 525.00
2014-08-25 34.55
2014-08-27 52.78
2014-08-31 30.00
I need to convert the MySQL query code to SQLite. I did a google search and found some info about using CASE but I am not sure how to construct the sql statement. Your help is appreciated

Your SQL query actually doesn't make sense in MySQL, because several of the selected values are indeterminate. You might try something like this:
SELECT ed.expenseDate, SUM(e.cost) as total,
group_concat(e.name) as names,
group_concat(c.category) as categories
FROM expenses e INNER JOIN
category c
ON e.catID = e.catID INNER JOIN
expense_date ed
ON e.dateID = ed.dateID
WHERE ed.expenseDate BETWEEN '#from#' AND '#tu#' AND
e.catID <> '1F27C7A1-3E16-5087-A313-A47D286A77A5' AND
e.catID <> 'DF64C183-5056-A816-1ACA94F902242B61' AND
e.userID = '#userID#' AND
e.accountID = '#accountID#'
Group By ed.expenseDate;

This is the SQLite sql statement that solved my problem.
SELECT expense_date.expenseDate,
SUM(expenses.cost) AS total
FROM expenses INNER JOIN expense_date ON expenses.dateID = expense_date.dateID
WHERE expense_date.expenseDate BETWEEN '"+from+"' AND '"+tu+"'
AND expenses.catID <> '1F27C7A1-3E16-5087-A313-A47D286A77A5'
AND expenses.catID <> 'DF64C183-5056-A816-1ACA94F902242B61' Group By expense_date.expenseDate
Thanks for everyones help.

Related

How to avoid GROUP_CONCAT() rows multiplying my SUM()

So I have a query who retrieves support tickets and with GROUP_CONCAT() im retrieving each ticket statuses on one row, to proccess in PHP as an array.
My problem is that on the query I have a SUM() to get time expent on each ticket from his interventions but, for example, if GROUP_CONCAT() retrieves 12 statuses and the ticket summation is 2400 seconds, the final result of SUM() is 2400 x 12 = 28800.
Here is my query:
SELECT t.subject as theme, SUM(fd.duree) as time, t.datec, t.date_close, t.category_code as category, GROUP_CONCAT(DISTINCT IFNULL(tl.status, 0),'_',tl.datec ORDER BY tl.datec) as status
FROM llx_ticketsup as t
JOIN llx_societe as s on s.rowid = t.fk_soc
JOIN llx_user as u on u.rowid = t.fk_user_assign
JOIN llx_element_element as ee on ee.fk_source = t.rowid
JOIN llx_fichinter as f on f.rowid = ee.fk_target
JOIN llx_fichinterdet as fd on fd.fk_fichinter = f.rowid
JOIN llx_ticketsup_logs as tl on tl.fk_track_id = t.track_id
WHERE t.fk_statut = 8
AND t.fk_soc = 165
AND (STR_TO_DATE(t.date_close, '%Y-%m-%d') BETWEEN '2018-06-25' AND '2018-06-25 23:59:59')
GROUP BY t.rowid
Result:
It should have 2400 on time, but is multiplying by his 12 statuses.
If I group by statuses too, time is well as you can see, but I need only one row with ticket real time expent and his statuses concatenated.
My question is, how can avoid GROUP_CONCAT() rows not to multiplying my SUM() ?
*EDIT: I made it work by dividing SUM(fd.duree)/COUNT(DISTINCT tl.rowid). I know it's a weird fix but don't know how to do otherwise. If anybody has any suggestion would appreciate it. Thanks!
SELECT t.subject as theme,
SUM(fd.duree) as time,
t.datec, t.date_close,
t.category_code as category,
(SELECT GROUP_CONCAT(DISTINCT COALESCE(l.status, 0),'_',l.datec ORDER BY l.datec)
FROM llx_ticketsup_logs AS l WHERE fk_track_id = t.track_id) as status
FROM llx_ticketsup as t
JOIN llx_element_element as ee on ee.fk_source = t.rowid
JOIN llx_fichinter as f on f.rowid = ee.fk_target
JOIN llx_fichinterdet as fd on fd.fk_fichinter = f.rowid
WHERE t.fk_statut = 8
AND t.fk_soc = 165
AND (STR_TO_DATE(t.date_close, '%Y-%m-%d') BETWEEN '2018-06-25' AND '2018-06-25 23:59:59')
GROUP BY t.rowid

how to optimize mysql query with inner join

select id from customer_details where store_client_id = 2
And
id NOT IN (select customer_detail_id from orders
where store_client_id = 2 and total_spent > 100 GROUP BY customer_detail_id )
Or
id IN (select tcd.id from property_details as pd, customer_details as tcd
where pd.store_client_id = 2 and pd.customer_detail_id = tcd.customer_id and pd.property_key = 'Accepts Marketing'
and pd.property_value = 'no')
And
id IN (select customer_detail_id from orders
where store_client_id = 2 GROUP BY customer_detail_id HAVING count(customer_detail_id) > 0 )
Or
id IN (select tor.customer_detail_id from ordered_products as top, orders as tor
where tor.id = top.order_id and tor.store_client_id = 2
GROUP BY tor.customer_detail_id having sum(top.price) = 1)`
I have this mysql query with inner join so when it run in mysql server it slow down what is the issue cant find.
But after 4-5 minutes it return 15 000 records. This records is not an issue may be.
In some tutorial suggest to use Inner join, Left join,...
But I don't know how to convert this query in Join clause.
Any help will be appreciated. Thanks in advance.
First of all please read relational model and optimizing select statements.

Incorrect SUM when using two LEFT JOINs and a GROUP BY

The following code returns an incorrect value for the sumHours field. It appears to prepare the sumHours field then once the GROUP BY runs, sum the sums together.
SELECT mmr_ID, mmr_projectName, SUM(mmr_hoursWorked.mmr_hoursWorked_hours) AS sumHours
FROM mmr
LEFT JOIN mmr_hoursWorked
ON mmr.mmr_ID = mmr_hoursWorked.mmr_hoursWorked_project AND mmr_hoursWorked.mmr_hoursWorked_mm = "P90826"
LEFT JOIN mmr_notes
ON mmr.mmr_ID = mmr_notes.mmr_notes_MMR_ref AND mmr_notes.mmr_notes_author = "P90826"
WHERE mmr_mmAssigned = "P90826" AND mmr_projectStatus != 1 OR mmr_notes.mmr_notes_author = "P90826" AND mmr_projectStatus != 1
GROUP BY mmr_ID
Actual Results
mmr_ID - 35
mmr_projectName - Project A
sumHours - 140.2
Expected Results
mmr_ID - 35
mmr_projectName - Project A
sumHours - 35.05
Due to JOIN statements combination of results are returned, so you should handle aggregates and joins separately. Try this:
SELECT t.*
FROM
(
SELECT mmr_ID, mmr_projectName, SUM(mmr_hoursWorked.mmr_hoursWorked_hours) AS sumHours
FROM mmr
LEFT JOIN mmr_hoursWorked
ON mmr.mmr_ID = mmr_hoursWorked.mmr_hoursWorked_project AND mmr_hoursWorked.mmr_hoursWorked_mm = 'P90826'
WHERE mmr_projectStatus != 1 AND mmr_mmAssigned = 'P90826'
GROUP BY mmr_ID, mmr_projectName, mmr_mmAssigned
) t
LEFT JOIN mmr_notes
ON t.mmr_ID = mmr_notes.mmr_notes_MMR_ref
WHERE mmr_notes.mmr_notes_author = 'P90826';
The issue was corrected by normalizing the database. The mmr_notes table was integrated into the mmr_hoursWorked table since it only had one unique field.

select count(*) with left join

I have a query where I try to retrieve the number of rows but in my case drops as result 1 on each time. I suppose that is a join problem and I don't kniw how to handle this
SELECT
COUNT(*) AS summe
FROM
feeds
LEFT JOIN cat_product cp
ON cp.product_id = feeds.productid
WHERE 1 = 1
AND cp.price BETWEEN 950
AND 1450
AND cp.ram_cap BETWEEN 5
AND 11
AND feeds.tdcategoryname LIKE '%Laptop%'
AND feeds.brand IN ('Dell', 'Lenovo', 'Acer', 'Asus')
GROUP BY cp.product_id
Try this, not sure if you are using MySQL or MSSQL. Since you LEFT JOIN there is a possibility that a value is NULL. In MSSQL if a NULL value is accounted for the the result will be NULL Always when using a aggregated function like COUNT.
For MySQL
SELECT
COUNT(IFNULL(cp.Procuct_id,0)) AS summe
FROM
feeds
LEFT JOIN cat_product cp
ON cp.product_id = feeds.productid
WHERE 1 = 1
AND cp.price BETWEEN 950
AND 1450
AND cp.ram_cap BETWEEN 5
AND 11
AND feeds.tdcategoryname LIKE '%Laptop%'
AND feeds.brand IN ('Dell', 'Lenovo', 'Acer', 'Asus')

Subquery invalid result with MySQL

I've an issue with the columns result from a subquery.
When I write the query:
select Q1.numi, Q1.sir from (select numi, sir from cust_vehicle where topg = 'VU') Q1
inner join (select id_contact, sir, ni from cust_contact) Q2 on Q1.sir = Q2.sir
I get 2 output columns (numi and sir).
But if I transform the query above as a subquery like:
select Q3.*
from (
select Q1.numi, Q1.sir from (select numi, sir from cust_vehicle where topg = 'VU') Q1
inner join (select id_contact, sir, ni from cust_contact) Q2 on Q1.sir = Q2.sir
) Q3
I get only the first column as output (the numi field).
Why do I have this behaviour?
For information, I use MySQL 5.6.11 on OS X 10.8
I found the origin of the problem. It's MySQL Workbench.
I opened a new SQL sheet and pasted my query in it. Now, all work fine.
Thanks for your help :)
SELECT cv.numi
, cv.sir
, cc.id_contact
, cc.ni
FROM cust_vehicle cv
JOIN cust_contact cc
ON cc.sir = cv.sir
WHERE cv.topg = 'VU'