I understand about how to use the count with the group by, but I need a specific use of this reverse, I try to do this query:
SELECT
COUNT(pac.strid_paciente)
FROM tb_paciente AS pac
LEFT JOIN tb_entidades AS ent
ON pac.strid_entidad = ent.strid_entidad
LEFT JOIN tb_escolaridad AS esc
ON pac.strid_escolaridad = esc.strID_Escolaridad
LEFT JOIN tb_etnia AS etn
ON pac.strid_etnia = etn.strID_Etnia
LEFT JOIN tb_raza AS raza
ON pac.strid_raza = raza.strid_raza
LEFT JOIN tb_religion AS rel
ON pac.strid_religion = rel.strid_religion
LEFT JOIN tb_ocupacion AS ocu
ON pac.strOfi_Paciente = ocu.strID_Ocupacion
LEFT JOIN tb_consulta AS con
ON pac.strid_paciente = con.strid_paciente
LEFT JOIN tb_usuarios AS usu
ON usu.strid_usuario = con.strid_medico
GROUP BY pac.strid_paciente
And it gives me:
COUNT(pac.strid_paciente)
1
1
2
3
4
5
2
I need the result of every count: 18, the problem is that I cant delete the group by because give a different result. Something like that:
COUNT(pac.strid_paciente)
18
Have you tried SUM( COUNT(pac.strid_paciente) ) OR if that fails then the following will work:
SELECT SUM( t.cnt ) FROM(
SELECT
COUNT(pac.strid_paciente) AS cnt
FROM tb_paciente AS pac
LEFT JOIN tb_entidades AS ent
ON pac.strid_entidad = ent.strid_entidad
LEFT JOIN tb_escolaridad AS esc
ON pac.strid_escolaridad = esc.strID_Escolaridad
LEFT JOIN tb_etnia AS etn
ON pac.strid_etnia = etn.strID_Etnia
LEFT JOIN tb_raza AS raza
ON pac.strid_raza = raza.strid_raza
LEFT JOIN tb_religion AS rel
ON pac.strid_religion = rel.strid_religion
LEFT JOIN tb_ocupacion AS ocu
ON pac.strOfi_Paciente = ocu.strID_Ocupacion
LEFT JOIN tb_consulta AS con
ON pac.strid_paciente = con.strid_paciente
LEFT JOIN tb_usuarios AS usu
ON usu.strid_usuario = con.strid_medico
GROUP BY pac.strid_paciente
) AS t
Related
I'm having problems with a MySQL Query. I have read a lot of the currently answered threads, following a lot of examples but I have not been able to solve my trouble so I come to you for help. Thanks in advance.
I have this query:
SELECT ventas.*,
clientes.nombre AS CLIENT_NOMBRE,
clientes.telefono AS TELEFONO,
users.nombre AS USERNAME,
canales_ventas.nombre AS CAN_VENTA,
estados_venta.nombre AS ESTADOS,
metodos_pago.nombre AS MET_PAGO,
canales_entrega.nombre AS CAN_ENTREGA,
canales_entrega.categoria AS CAN_ENTREGA_CAT,
COALESCE(perc.qty,0) AS DESC_PERCENT,
COALESCE(fix.qty,0) AS DESC_FIXED,
COALESCE(SUM(ventas_productos.vp_cantidad*ventas_productos.vp_precio),0) AS Total_Value
FROM ventas
JOIN clientes ON clientes.id = ventas.cliente_id
JOIN users ON users.id = ventas.vendedor_id
LEFT OUTER JOIN canales_ventas ON canales_ventas.id = ventas.canal_venta_id
LEFT OUTER JOIN estados_venta ON estados_venta.id = ventas.estado_actual
LEFT OUTER JOIN metodos_pago ON metodos_pago.id = ventas.metodo_pago
LEFT OUTER JOIN canales_entrega ON canales_entrega.id = ventas.metodo_entrega
LEFT OUTER JOIN ventas_descuentos perc ON perc.orden_id = ventas.id AND perc.tipo = 1
LEFT OUTER JOIN ventas_descuentos fix ON fix.orden_id = ventas.id AND fix.tipo = 2
LEFT JOIN ventas_productos ON ventas_productos.vp_orden_id = ventas.id GROUP BY ventas.id
But I need that all the results match ventas.estado_actual = 7
I'd appreciate a lot the help. Thanks!
EDIT1:
I have tried Using WHERE in these ways:
After the last Join:
SELECT ventas.*,
clientes.nombre AS CLIENT_NOMBRE,
clientes.telefono AS TELEFONO,
users.nombre AS USERNAME,
canales_ventas.nombre AS CAN_VENTA,
estados_venta.nombre AS ESTADOS,
metodos_pago.nombre AS MET_PAGO,
canales_entrega.nombre AS CAN_ENTREGA,
canales_entrega.categoria AS CAN_ENTREGA_CAT,
COALESCE(perc.qty,0) AS DESC_PERCENT,
COALESCE(fix.qty,0) AS DESC_FIXED,
COALESCE(SUM(ventas_productos.vp_cantidad*ventas_productos.vp_precio),0) AS Total_Value
FROM ventas
JOIN clientes ON clientes.id = ventas.cliente_id
JOIN users ON users.id = ventas.vendedor_id
LEFT OUTER JOIN canales_ventas ON canales_ventas.id = ventas.canal_venta_id
LEFT OUTER JOIN estados_venta ON estados_venta.id = ventas.estado_actual
LEFT OUTER JOIN metodos_pago ON metodos_pago.id = ventas.metodo_pago
LEFT OUTER JOIN canales_entrega ON canales_entrega.id = ventas.metodo_entrega
LEFT OUTER JOIN ventas_descuentos perc ON perc.orden_id = ventas.id AND perc.tipo = 1
LEFT OUTER JOIN ventas_descuentos fix ON fix.orden_id = ventas.id AND fix.tipo = 2
LEFT JOIN ventas_productos ON ventas_productos.vp_orden_id = ventas.id GROUP BY ventas.id
WHERE ventas.estado_actual = 7
ERROR #1064 - Something is wrong in your syntax 'LIMIT 0, 25' on line 23
In the From Clause:
SELECT ventas.*,
clientes.nombre AS CLIENT_NOMBRE,
clientes.telefono AS TELEFONO,
users.nombre AS USERNAME,
canales_ventas.nombre AS CAN_VENTA,
estados_venta.nombre AS ESTADOS,
metodos_pago.nombre AS MET_PAGO,
canales_entrega.nombre AS CAN_ENTREGA,
canales_entrega.categoria AS CAN_ENTREGA_CAT,
COALESCE(perc.qty,0) AS DESC_PERCENT,
COALESCE(fix.qty,0) AS DESC_FIXED,
COALESCE(SUM(ventas_productos.vp_cantidad*ventas_productos.vp_precio),0) AS Total_Value
FROM ventas WHERE ventas.estado_actual = 7
JOIN clientes ON clientes.id = ventas.cliente_id
JOIN users ON users.id = ventas.vendedor_id
LEFT OUTER JOIN canales_ventas ON canales_ventas.id = ventas.canal_venta_id
LEFT OUTER JOIN estados_venta ON estados_venta.id = ventas.estado_actual
LEFT OUTER JOIN metodos_pago ON metodos_pago.id = ventas.metodo_pago
LEFT OUTER JOIN canales_entrega ON canales_entrega.id = ventas.metodo_entrega
LEFT OUTER JOIN ventas_descuentos perc ON perc.orden_id = ventas.id AND perc.tipo = 1
LEFT OUTER JOIN ventas_descuentos fix ON fix.orden_id = ventas.id AND fix.tipo = 2
LEFT JOIN ventas_productos ON ventas_productos.vp_orden_id = ventas.id GROUP BY ventas.id
ERROR - #1064 Again the same error
where clause must be before group by
WHERE ventas.estado_actual = 7 GROUP BY ventas.id
I have the following query and would like to convert it to using a left outer join instead of a not in to see if it would run faster that way. It's currently taking this query about 40 seconds to run on our database. I'm not familiar enough with using outer joins for this type of thing to convert it myself.
select
c.contact_id as contact_id,
c.orgid as organization_id,
c.first_name as first_name,
c.last_name as last_name,
a.address_state as state
from cnx_contact as c
inner join cnx_address as a on c.home_address_uid = a.address_uid
where a.address_state = 'OH'
and (c.orgid = 45 or c.orgid = 55)
and c.contact_id NOT IN (
select pc.contact_id
from cnx_contact as c
inner join cnx_address as a on c.home_address_uid = a.address_uid
inner join cnx_contact_group_participant as gp on c.contact_id = gp.contact_id
inner join cnx_contact_participant_role as cr on gp.participant_role_uid = cr.participant_role_uid
inner join cnx_contact_group as cg on gp.group_uid = cg.group_uid
inner join cnx_contact_group_participant as pgp on cg.primary_participant_uid = pgp.participant_uid
inner join cnx_contact as pc on pgp.contact_id = pc.contact_id
where (c.orgid = 45 or c.orgid = 55)
and cr.name = 'Applicant'
);
select
c.columns
from cnx_contact as c
inner join cnx_address as a on c.home_address_uid = a.address_uid
LEFT JOIN
(Subquery goes here) x
ON x.contact _id = c.contact_id
where a.participant_state = 'OH'
and c.orgid IN(45,55)
and x.contact_id IS NULL;
Normally the query below gives me only one result (row).
SELECT
`s`.`FIRMA_UNVANI` AS `FIRMA_UNVANI`,
`s`.`RECNO` AS `RECNO`,
`s`.`BOLGE` AS `BOLGE`,
`s`.`BOLGE_NO` AS `BOLGE_NO`,
`s`.`DURUM` AS `DURUM`,
l.ILCE,
IL.SEHIR,
count(i.recno) AS NUMBER_OF_WORKS
FROM
`SERVISLER` `s`
LEFT JOIN KULLANICI k ON (s.BOLGE = k.KULLANICI)
LEFT JOIN kullanici_cihaz kc ON (k.RECNO = kc.KUL_RECNO)
LEFT JOIN servisler_ilceler c ON (s.RECNO = c.SER_RECNO)
INNER JOIN ILCE l ON (l.RECNO = c.ILCE_RECNO)
INNER JOIN IL ON (IL.ID = l.ILID)
LEFT JOIN ISEMRI i ON (
i.bolge = s.bolge_no
AND i.`SERVIS_DURUMU` = 1
)
WHERE
1 = 1
GROUP BY
s.BOLGE
ORDER BY
IS_SAYISI
LIMIT 0,
15
I get only one result
+----------------+-------+------+---------+------+-----+----------+-----------------+
|FIRMA_UNVANI |RECNO |BOLGE |BOLGE_NO |DURUM |ILCE | SEHIR | NUMBER_OF_WORKS |
+----------------+-------+------+---------+------+-----+----------+-----------------+
|Pirana |2501 |Tekkt |58 |-1 |NT |Istanbul |1428 |
+----------------+-------+------+---------+------+-----+----------+-----------------+
Here the key is RECNO.
I want to count the results:
SELECT
count(0) AS _count
FROM
`SERVISLER` `s`
LEFT JOIN KULLANICI k ON (s.BOLGE = k.KULLANICI)
LEFT JOIN kullanici_cihaz kc ON (k.RECNO = kc.KUL_RECNO)
LEFT JOIN servisler_ilceler c ON (s.RECNO = c.SER_RECNO)
INNER JOIN ILCE l ON (l.RECNO = c.ILCE_RECNO)
INNER JOIN IL ON (IL.ID = l.ILID)
LEFT JOIN ISEMRI i ON (
i.bolge = s.bolge_no
AND i.`SERVIS_DURUMU` = 1
)
WHERE
1 = 1
GROUP BY
s.BOLGE
And I get this wired result:
1428
It was supposed to be 1. Isn't it?
The result is perfectly fine, since you are just counting a 0 for every row instead of i.recno, therefore both resulting in 1428.
To count the number of results, you could wrap your whole query like this to get a resultcount:
SELECT count(*) AS resultcount FROM (
SELECT
`s`.`FIRMA_UNVANI` AS `FIRMA_UNVANI`,
`s`.`RECNO` AS `RECNO`,
`s`.`BOLGE` AS `BOLGE`,
`s`.`BOLGE_NO` AS `BOLGE_NO`,
`s`.`DURUM` AS `DURUM`,
l.ILCE,
IL.SEHIR,
count(i.recno) AS NUMBER_OF_WORKS
FROM
`SERVISLER` `s`
LEFT JOIN KULLANICI k ON (s.BOLGE = k.KULLANICI)
LEFT JOIN kullanici_cihaz kc ON (k.RECNO = kc.KUL_RECNO)
LEFT JOIN servisler_ilceler c ON (s.RECNO = c.SER_RECNO)
INNER JOIN ILCE l ON (l.RECNO = c.ILCE_RECNO)
INNER JOIN IL ON (IL.ID = l.ILID)
LEFT JOIN ISEMRI i ON (
i.bolge = s.bolge_no
AND i.`SERVIS_DURUMU` = 1
)
GROUP BY
s.BOLGE
ORDER BY
IS_SAYISI
LIMIT 0, 15) AS temp
Also note, that WHERE 1=1 is not necessary.
You have used GROUP BY in your query so you will get each group count in result, For example if there 3 group then you will get 3 count result..
If you need to get count of result rows then please use sub query see below
SELECT count(0) AS _count FROM(
SELECT
*
FROM
`SERVISLER` `s`
LEFT JOIN KULLANICI k ON (s.BOLGE = k.KULLANICI)
LEFT JOIN kullanici_cihaz kc ON (k.RECNO = kc.KUL_RECNO)
LEFT JOIN servisler_ilceler c ON (s.RECNO = c.SER_RECNO)
INNER JOIN ILCE l ON (l.RECNO = c.ILCE_RECNO)
INNER JOIN IL ON (IL.ID = l.ILID)
LEFT JOIN ISEMRI i ON (
i.bolge = s.bolge_no
AND i.`SERVIS_DURUMU` = 1
)
WHERE
1 = 1
GROUP BY
s.BOLGE
) AS Temp;
Need a little help with subqueries
If I have a 1 query like this:
SELECT Learner.Learner_Id, Max(LearnerEmploymentStatus.DateEmpStatApp) AS LatestEmpDate, Learner.LearnRefNumber, Learner.FamilyName, Learner.GivenNames, EmploymentStatusMonitoring.ESMType
FROM (Learner LEFT JOIN LearnerEmploymentStatus ON LearnerEmploymentStatus.Learner_Id = LearnerEmploymentStatus.Learner_Id) LEFT JOIN EmploymentStatusMonitoring ON LearnerEmploymentStatus.LearnerEmploymentStatus_Id = EmploymentStatusMonitoring.LearnerEmploymentStatus_Id
WHERE EmploymentStatusMonitoring.ESMType="BSI"
GROUP BY Learner.Learner_Id, Learner.LearnRefNumber, Learner.FamilyName, Learner.GivenNames, EmploymentStatusMonitoring.ESMType
...and another like this:
SELECT Learner.Learner_Id, LearnerEmploymentStatus.DateEmpStatApp, EmploymentStatusMonitoring.ESMCode
FROM (Learner LEFT JOIN LearnerEmploymentStatus ON Learner.Learner_Id = LearnerEmploymentStatus.Learner_Id) LEFT JOIN EmploymentStatusMonitoring ON LearnerEmploymentStatus.LearnerEmploymentStatus_Id = EmploymentStatusMonitoring.LearnerEmploymentStatus_Id
...and I wanted to do a join between the 2 queries (LEFT JOIN on the common Learner_Id and LatestEmpDate / DateEmpStatApp fields), how would I go about doing all this work in a single query where the 2 queries above would be subqueries?
My attempt below is not being accepted (JOIN expression not supported):
SELECT sQ1.Learner_Id, sQ1.LearnRefNumber, sQ1.FamilyName, sQ1.GivenNames, sQ1.LatestEmpDate, sQ1.ESMType, sQ2.ESMCode
FROM
(SELECT Learner.Learner_Id, Max(LearnerEmploymentStatus.DateEmpStatApp) AS LatestEmpDate, Learner.LearnRefNumber, Learner.FamilyName, Learner.GivenNames, EmploymentStatusMonitoring.ESMType
FROM (Learner LEFT JOIN LearnerEmploymentStatus ON LearnerEmploymentStatus.Learner_Id = LearnerEmploymentStatus.Learner_Id) LEFT JOIN EmploymentStatusMonitoring ON LearnerEmploymentStatus.LearnerEmploymentStatus_Id = EmploymentStatusMonitoring.LearnerEmploymentStatus_Id
WHERE EmploymentStatusMonitoring.ESMType="BSI"
GROUP BY Learner.Learner_Id, Learner.LearnRefNumber, Learner.FamilyName, Learner.GivenNames, EmploymentStatusMonitoring.ESMType) As sQ1
LEFT JOIN
(SELECT Learner.Learner_Id, LearnerEmploymentStatus.DateEmpStatApp, EmploymentStatusMonitoring.ESMCode
FROM (Learner LEFT JOIN LearnerEmploymentStatus ON Learner.Learner_Id = LearnerEmploymentStatus.Learner_Id) LEFT JOIN EmploymentStatusMonitoring ON LearnerEmploymentStatus.LearnerEmploymentStatus_Id = EmploymentStatusMonitoring.LearnerEmploymentStatus_Id) As sQ2
ON (sQ1.Learner_Id = sQ2.Learner_Id) AND (sQ1.LatestEmpDate = sQ2.DateEmpStatApp);
Would something like this get you what you want...?
SELECT l.Learner_Id, d.LatestEmpDate, l.LearnRefNumber, l.FamilyName, l.GivenNames, m.ESMType, m.ESMCode
FROM ((Learner AS l
LEFT JOIN (
SELECT s.Learner_Id, MAX(s.DateEmpStatApp) AS LatestEmpDate
FROM LearnerEmploymentStatus AS s
GROUP BY s.Learner_Id) AS d ON d.Learner_Id = l.Learner_Id)
LEFT JOIN LearnerEmploymentStatus AS ls ON (ls.Learner_Id = d.Learner_Id) AND (ls.DateEmpStatApp = d.LatestEmpDate))
LEFT JOIN EmploymentStatusMonitoring AS m ON m.LearnerEmploymentStatus_Id = ls.LearnerEmploymentStatus_Id
WHERE m.ESMType = 'BSI'
Assumes the same learner won't have the same DateEmpStatApp twice, which may or not be valid.
I've got the query below that's pulling data from a number of tables to create an update:
UPDATE en_inter.subscribers_data AS sd
inner join en_inter.list_subscribers AS ls on sd.subscriberid = ls.subscriberid
LEFT JOIN (
SELECT pd1.email_address,COUNT(pd1.email_address) AS NumDowns
FROM email.papr_down pd1
INNER JOIN email.papr_data pd2 on pd1.paper_id = pd2.id
INNER JOIN email.papr_subj ps on ps.id = pd2.subject
INNER JOIN email.papr_exam pe on pe.id = pd2.exam
INNER JOIN email.papr_levl pl on pl.id = pd2.level
WHERE pd2.exam = 1
and pd2.level = 4
GROUP BY email_address
) AS downs ON downs.email_address = ls.emailaddress
SET sd.data = ifnull(downs.NumDowns,1)
WHERE sd.fieldid = 33;
It works fine but when there are plenty of records in papr_down then it takes ages to process. Any ideas about how it can be optimized?
What I think is the join between the emailAddress is the issue here, you can try out with the join with the Id's.
If you provide us the screen shot of the below query ::
EXPLAIN Select * from
en_inter.subscribers_data AS sd
inner join en_inter.list_subscribers AS ls on sd.subscriberid = ls.subscriberid
LEFT JOIN (
SELECT pd1.email_address,COUNT(pd1.email_address) AS NumDowns
FROM email.papr_down pd1
INNER JOIN email.papr_data pd2 on pd1.paper_id = pd2.id
INNER JOIN email.papr_subj ps on ps.id = pd2.subject
INNER JOIN email.papr_exam pe on pe.id = pd2.exam
INNER JOIN email.papr_levl pl on pl.id = pd2.level
WHERE pd2.exam = 1
and pd2.level = 4
GROUP BY email_address
) AS downs ON downs.email_address = ls.emailaddress
WHERE sd.fieldid = 33
As I know we should use joins only for the columns which are preset in SELECT clause and for other joins we should implement using WHERE clause
Please try following query:
UPDATE en_inter.subscribers_data AS sd
inner join en_inter.list_subscribers AS ls
on sd.subscriberid = ls.subscriberid
LEFT JOIN (
SELECT pd1.email_address,COUNT(pd1.email_address) AS NumDowns
FROM email.papr_down AS pd1
INNER JOIN email.papr_data AS pd2 on pd1.paper_id = pd2.id
WHERE
email.papr_exam.id in (select exam from email.papr_data where exam = 1)
AND
email.papr_levl.id in (select level from email.papr_data where level = 4 )
AND
email.papr_subj.id in (select subject from email.papr_data)
GROUP BY email_address
) AS downs ON downs.email_address = ls.emailaddress
SET sd.data = ifnull(downs.NumDowns,1)
WHERE sd.fieldid = 33;
I can not execute this at my machine since i don't have the schema