MySQL with multiple SELECT and GROUP BY - mysql

I have a problem with my database in mysql. I would like to have a table from my database with date, pat, dureeP, dureeC but this function doesn't GROUP BY :
select *
from (SELECT date_format(p.date, "%Y-%m") AS date
,p.pat
,AVG(a) AS dureeP
FROM timing as t, patient as p
WHERE t.id_p = p.id_p
AND t.pos=6
AND t.heure_fin IS NOT NULL
GROUP BY p.pat, MONTH(p.date), YEAR(p.datede)
) as T1,
(SELECT AVG(b) AS dureeC
FROM timing as t, patient as p
WHERE t.id_p = p.id_p
AND t.pos=3
AND t.heure_fin IS NOT NULL
GROUP BY p.pathologie, MONTH(p.date), YEAR(p.date)
) as T2
With one SELECT I can have what I want but with multiple SELECT I can Group By.
Do you have an idea?
Thank you

To simplify your query you might be able to use "conditional aggregates" which basically means placing a case expression inside an aggregate function
SELECT
p.pathologie
, MONTH(p.date)
, YEAR(p.date)
, AVG(CASE WHEN t.pos = 3 THEN b END) AS dureeC
, AVG(CASE WHEN t.pos = 6 THEN a END) AS dureeP
FROM timing AS t
INNER JOIN patient AS p ON t.id_p = p.id_p
WHERE t.heure_fin IS NOT NULL
GROUP BY
p.pathologie
, MONTH(p.date)
, YEAR(p.date)

Related

Query optimization needed because of too many sub queries and sub query dependency in where conditions

I'm writing code for the production report.
I had written this query
SELECT
P.*,
(
SELECT
COUNT(id) AS cnt
FROM
bales
WHERE
create_date < '2019-11-01' AND product_id = P.id AND(TYPE = 'bale' OR TYPE = 'bag')
) AS before_prod,
(
SELECT
COUNT(id) AS cnt
FROM
bales
WHERE
(
dispatched = '0' OR disp_bunch = '0'
) AND dispatch_date < '2019-11-01' AND product_id = P.id AND(TYPE = 'bale' OR TYPE = 'bag')
) AS before_dispatched,
(
SELECT
COUNT(id) AS cnt
FROM
bales
WHERE
create_date BETWEEN '2019-11-01' AND '2019-11-06' AND product_id = P.id AND(TYPE = 'bale' OR TYPE = 'bag')
) AS production,
(
SELECT
COUNT(id) AS cnt
FROM
bales
WHERE
(
dispatched = '0' OR disp_bunch = '0'
) AND dispatch_date BETWEEN '2019-11-01' AND '2019-11-06' AND product_id = P.id AND(TYPE = 'bale' OR TYPE = 'bag')
) AS production_dispatched,
C.name AS category_name
FROM
products P
INNER JOIN category C ON
C.id = P.category
This query is working but as I have too many records in all tables it takes too much time.
also, I need only records where before_prod, before_dispatched, production, production_dispatched all these subquery results should be greater than 0.
I tried to use having clause but it also takes too much time.
I have also tried php for loop, * LOGIC: first all products than in for loop its production. but it was much slower.*
How can I optimize my query?
You can use join instead and select case to sum your data that matches your conditions.
select p.*, t.*
from products p
inner join (
select t2.id, sum(case when create_date < '2019-11-01' then 1 else 0 end) as before_prod
, sum(case when (dispatched = '0' or disp_bunch = '0') and create_date < '2019-11-01' then 1 else 0 end) as before_dispatched
, sum(case when create_date between '2019-11-01' and '2019-11-06' then 1 else 0 end) as production
, sum(case when (dispatched = '0' or disp_bunch = '0') and create_date between '2019-11-01' and '2019-11-06' then 1 else 0 end) as production_dispatched
from bales t1
inner join product t2 on t2.id= t1.product_id
inner join category t3 on t3.id = t2.category
where t1.TYPE in ('bale', 'bag')
group by t2.id) t
on t.id = p.id

MySQL: Grouped by hour, need to show all hours, null where no data

Here's the query:
SELECT h.idhour, h.`hour`, outnumber, count(*) as `count`, sum(talktime) as `duration`
FROM (
SELECT
`cdrs`.`dcustomer` AS `dcustomer`,
(CASE
WHEN (`cdrs`.`cnumber` like "02%") THEN '02'
WHEN (`cdrs`.`cnumber` like "05%") THEN '05'
END) AS `outnumber`,
FROM_UNIXTIME(`cdrs`.`start`) AS `start`,
(`cdrs`.`end` - `cdrs`.`start`) AS `duration`,
`cdrs`.`talktime` AS `talktime`
FROM `cdrs`
WHERE `cdrs`.`start` >= #_START and `cdrs`.`start` < #_END
AND `cdrs`.`dtype` = _LATIN1'external'
GROUP BY callid
) cdr
JOIN customers c ON c.id = cdr.dcustomer
LEFT JOIN hub.hours h ON HOUR(cdr.`start`) = h.idhour
WHERE (c.parent = _ID or cdr.dcustomer = _ID or c.parent IN
(SELECT id FROM customers WHERE parent = _ID))
GROUP BY h.idhour, cdr.outnumber
ORDER BY h.idhour;
The above query results skips the hours where there is no data, but I need to show all hours (00:00 to 23:00) with null or 0 values. How can I do this?
SELECT h.idhour
, h.hour
,IFNULL(outnumber,'') AS outnumber
,IFNULL(cdr2.duration,0) AS duration
,IFNULL(output_count,0) AS output_count
FROM hub.hours h
LEFT JOIN (
SELECT HOUR(start) AS start,outnumber, SUM(talktime) as duration ,COUNT(1) AS output_count
FROM
(
SELECT cdrs.dcustomer AS dcustomer
, (CASE WHEN (cdrs.cnumber like "02%") THEN '02' WHEN (cdrs.cnumber like "05%") THEN '05' END) AS outnumber
, FROM_UNIXTIME(cdrs.start) AS start
, (cdrs.end - cdrs.start) AS duration
, cdrs.talktime AS talktime
FROM cdrs cdrs
INNER JOIN customers c ON c.id = cdrs.dcustomer
WHERE cdrs.start >= #_START and cdrs.start < #_END AND cdrs.dtype = _LATIN1'external'
AND
(c.parent = _ID or cdrs.dcustomer = _ID or c.parent IN (SELECT id FROM customers WHERE parent = _ID))
GROUP BY callid
) cdr
GROUP BY HOUR(start),outnumber
) cdr2
ON cdr2.start = h.idhour
ORDER BY h.idhour
You need a table with all hours, nothing else.
Then use LEFT JOIN with the hours table on the "left" and your current query on the "right":
SELECT b.*
FROM hours h
LEFT JOIN ( ... ) b ON b.hr = h.hr
WHERE h.hr BETWEEN ... AND ...
ORDER BY hr;
Any missing hours will be NULLs in b.*.

how I can get the next data in mysql

really do not know if you can, but i I need the DATE VENC to be equal to '2013-02-02'.
the values of the column date_pay:
1-2013-01-01
2-2013-02-02
3-0000-00-00
4-0000-00-00
this is my query:
SELECT s.id,
s.name,
s.nro_s,
ts.cat,
SUM( ts.pryce ) AS deuda,
SUM( ts.pryce ) DIV ts.pryce AS c_p,
date_venc = (select max(date_pay) from c ) // the date in question
FROM s
INNER JOIN c
INNER JOIN ts
WHERE s.id = '123'
AND c.id = '123'
AND c.date_pay = '0000-00-00'
AND s.ts = ts.id_ts
Sorry for my english, is very basic.
Greetings.
Assuming date_venc is DATE a possible solution
select *
from s
where s.date_venc=
(select max(cast(SUBSTRING_INDEX(date_pay,'-',-3)as DATE))from c);
also check out sqlfiddle
http://sqlfiddle.com/#!2/64197/1
and your query should probably be modified to,
SELECT s.id,
s.name,
s.nro_s,
ts.cat,
SUM( ts.pryce ) AS deuda,
SUM( ts.pryce ) DIV ts.pryce AS c_p,
date_venc
FROM s
INNER JOIN c
INNER JOIN ts
WHERE s.id = '123'
AND c.id = '123'
AND c.date_pay = '0000-00-00'
AND s.ts = ts.id_ts
AND date_venc = (select max(cast(SUBSTRING_INDEX(date_pay,'-',-3)as DATE)) from c ) // the date in question

MySQL Optimizing Query With IN

SELECT `listener` ,
SEC_TO_TIME( SUM( TIME_TO_SEC( `call_time` ) ) ) AS total_time,
COUNT( `listener` ) AS number
FROM calls
WHERE listened_date = '2013-05-09'
AND type in ('column1','column2')
AND id
IN ( SELECT id
FROM calls
GROUP BY CONCAT( name, ' ', when ) )
GROUP BY `listener`
This query is working so slow and making other queries not working in same time. How can i make this lighter?
I think IN make it slower. What is alternative in this case?
Maybe ?:
SELECT c.`listener` ,
SEC_TO_TIME(SUM(TIME_TO_SEC(c.`call_time`))) AS total_time,
COUNT(c.`listener`) AS number
FROM calls c
WHERE c.listened_date = '2013-05-09'
AND c.TYPE IN ('column1',
'column2')
AND EXISTS (SELECT 0
FROM calls c2
WHERE c2.id = c.id)
GROUP BY c.`listener`

MySQL - Combining multiple queries + counts

I'm attempting to combine a few queries and can't seem to nail it down. I was wondering if someone could point me in the right direction.
Here are the statements:
SELECT
I.id,
I.custname,
I.custemail,
I.sku,
DATE_FORMAT(FROM_UNIXTIME(I.ts), '%l:%i:%s %p, %c/%e/%Y') AS ts
FROM images I
WHERE I.stat = 0
SELECT
COUNT(*) AS total1
FROM images
WHERE stat = 1 AND sku = ?
SELECT
COUNT(*) AS total2
FROM images
WHERE stat = 1
AND sku IN (SELECT subsku FROM combo WHERE sku = ?)
Right now I'm using the 3 separate queries and am using code to add the two totals and display them. But I now need to be able to sort by the sum of the totals, so I'd like to get all of that data into one statement.. something like:
SELECT
I.id,
I.custname,
I.custemail,
I.sku,
DATE_FORMAT(FROM_UNIXTIME(I.ts), '%l:%i:%s %p, %c/%e/%Y') AS ts,
SUM(total1+total2)
FROM images I
WHERE I.stat = 0
But I'm unsure how to do that. I tried the code below, but it failed:
SELECT
I.id,
I.custname,
I.custemail,
I.sku,
DATE_FORMAT(FROM_UNIXTIME(I.ts),'%l:%i:%s %p, %c/%e/%Y') AS ts,
(
SELECT COUNT(*) AS total1 FROM images WHERE stat = 1 AND (
sku IN (
SELECT subsku FROM combo WHERE sku = I.sku
) OR sku = I.sku)
) AS skuct
FROM images I
WHERE stat = 0
Any help would be greatly appreciated. Many thanks!
UPDATE
First off thanks to everyone who has offered assistance. I've been working on the query and think I'm getting closer, but I'm now hitting a 'subquery returns more than 1 row' error:
SELECT
I.id,
I.custname,
I.custemail,
I.sku,
DATE_FORMAT(FROM_UNIXTIME(I.ts), '%l:%i:%s %p, %c/%e/%Y') AS ts,
(
SELECT COUNT(*)
FROM images
WHERE stat = 1
AND sku = I.sku
OR sku IN(
SELECT subsku FROM combo WHERE sku = I.sku
)
GROUP BY sku
) AS total
FROM images I
WHERE stat = 0
The problem is that the subquery SELECT subsku FROM combo WHERE... returns a resultset (0+ rows) vs a scalar. If I can figure out that part, I think this will work.
Select I.id, I.custname, I.custemail, I.sku
, DATE_FORMAT(FROM_UNIXTIME(I.ts), '%l:%i:%s %p, %c/%e/%Y') AS ts
, (
Select Sum( Case
When I1.sku = ? Then 1
When I1.sku In( Select subsku From combo As S1 Where S1.sku = ? ) Then 1
Else 0
End ) As Total
From images As I1
Where I1.stat = 1
) As Total
From images As I
Where stat = 0
Another solution
Select I.id, I.custname, I.custemail, I.sku
, DATE_FORMAT(FROM_UNIXTIME(I.ts), '%l:%i:%s %p, %c/%e/%Y') AS ts
, (
Select Count(*)
From images As I1
Where I1.stat = 1
And (
I1.sku = ?
Or I1.sku In ( Select subsku From combo As S1 Where S1.sku = ? )
)
) As Total
From images As I
Where stat = 0
Addition
Another possible solution:
Select I.id, I.custname, I.custemail, I.sku
, DATE_FORMAT(FROM_UNIXTIME(I.ts), '%l:%i:%s %p, %c/%e/%Y') AS ts
, (
Select Sum( Cnt )
From (
Select Count(*) As Cnt
From images As I1
Left Join combo As C1
On C1.sku = I1.sku
Where I1.stat = 1
And I1.sku = ?
And C1.PrimaryKeyCol Is Null
Union All
Select Count( Distinct I1.PrimaryKeyCol )
From images As I1
Join combo As C1
On C1.sku = I1.sku
Where I1.stat = 1
And I1.sku = ?
) As Z
) As Total
From images As I
Where stat = 0
Edit
If you are looking for the count by image in which you correlate the counts to the outer table images sku column, that's entirely different. For that, I would use a derived table:
Select I.id, I.custname, I.custemail, I.sku
, DATE_FORMAT(FROM_UNIXTIME(I.ts), '%l:%i:%s %p, %c/%e/%Y') AS ts
, Counts.Total
From images As I
Join (
Select Z.sku, Sum(Z.Cnt) As Total
From (
Select I1.sku, Count(*) As Cnt
From images As I1
Left Join combo As C1
On C1.sku = I1.sku
Where I1.stat = 1
And C1.PrimaryKeyCol Is Null
Group By I1.sku
Union All
Select I1.sku, Count( Distinct I1.PrimaryKeyCol )
From images As I1
Join combo As C1
On C1.sku = I1.sku
Where I1.stat = 1
Group By I1.sku
) As Z
Group By Z.sku
) As Counts
On Counts.sku = I.sku
Where stat = 0
Obviously in all cases, replace PrimaryKeyCol with the name of the actual primary key column of the images table.
Have you considered changing the WHERE logic to perform the count in one.
Assuming the two counts are mutually exclusive you could just OR the two conditions.
Use the cross join . . .
select t1.*, t2.total1, t3.total2
from
(
SELECT I.id, I.custname, I.custemail, I.sku,
DATE_FORMAT(FROM_UNIXTIME(I.ts), '%l:%i:%s %p, %c/%e/%Y') AS ts
FROM images I
WHERE I.stat = 0
) t1
cross join
(
SELECT COUNT(*) AS total1
FROM images
WHERE stat = 1 AND sku = ?
) t2
cross join
(
SELECT COUNT(*) AS total2
FROM images
WHERE stat = 1 AND sku IN (SELECT subsku FROM combo WHERE sku = ?)
) t3
You might be able to make this more efficient, since they are all going after the same table. A single aggregation with a case statement per WHERE clause would probably be more efficient.