I want to count the patient diagnosis per municipality and consultation per municipality:
so it should be:
diagnosis per municipality + consultation per municipality
SELECT COUNT(consultations.id) +
(SELECT COUNT(patientdiagnosis.id)
FROM consultations
LEFT JOIN patientdiagnosis
ON patientdiagnosis.consultation_id = consultations.id
LEFT JOIN patients
ON consultations.patient_id = patients.id
LEFT JOIN rcitymun
ON patients.municipality = rcitymun.citycode
/*GROUP BY PER MUNICIPALITY SHOULD BE HERE*/
) as encounters, rcitymun.cityname
FROM consultations
LEFT JOIN patients
ON consultations.patient_id = patients.id
LEFT JOIN rcitymun
ON patients.municipality = rcitymun.citycode
GROUP BY patients.municipality;
current output:
encounters municipality
10323 BATAC
10423 NUEVA ERA
the encounter data is huge because it's counting all of the diagnosis instead of per municipality
what i want is to count the diagnosis per municipality.
desired output is something like this:
encounters municipality
105 BATAC
70 NUEVA ERA
It may be possible to reduce this by one subquery, but often it is best to start with independently grouped subqueries.
SELECT
rcitymun.cityname
, SUM(c.consult_count) consult_count
, SUM(d.diag_count) diag_count
FROM patients
INNER JOIN rcitymun ON patients.municipality = rcitymun.citycode
LEFT JOIN (
SELECT
consultations.patient_id
, COUNT(*) consult_count
FROM consultations
GROUP BY
consultations.patient_id
) c ON patients.id = c.patient_id
LEFT JOIN (
SELECT
consultations.patient_id
, COUNT(*) diag_count
FROM consultations
INNER JOIN patientdiagnosis ON patientdiagnosis.consultation_id = consultations.id
GROUP BY
consultations.patient_id
) d ON patients.id = d.patient_id
GROUP BY
rcitymun.cityname
Related
I need have created a select statement to list out all the customers that have been to multiple merchants below.
I want to create another statement to display how many of those customers have been to each merchant.
What is the optimal method of approaching this problem?
Lists out all customers that have been to multiple merchants.
WITH valentinesDayMerchant AS (
SELECT m.MerchantId, m.MerchantGroupId, m.WebsiteName
FROM Merchant m
INNER JOIN OpeningHours oh ON m.MerchantId = oh.MerchantId AND oh.DayOfWeek = 'TUE'
LEFT JOIN devices.DeviceConnectionState AS dcs ON dcs.MerchantId = oh.MerchantId
WHERE MerchantStatus = '-' AND (m.PrinterType IN ('V','O') OR dcs.State = 1 OR dcs.StateTransitionDateTime > '2023-01-23')
)
SELECT DISTINCT ul.UserLoginId, ul.FullName, ul.EmailAddress, ul.Mobile
FROM dbo.UserLogin AS ul
INNER JOIN dbo.Patron AS p ON p.UserLoginId = ul.UserLoginId
INNER JOIN valentinesDayMerchant AS m ON (m.MerchantId = ul.ReferringMerchantId OR m.MerchantId IN (SELECT pml.MerchantId FROM dbo.PatronMerchantLink AS pml WHERE pml.PatronId = p.PatronId AND ISNULL(pml.IsBanned, 0) = 0))
LEFT JOIN (
SELECT mg.MerchantGroupId, mg.MerchantGroupName, groupHost.HostName [GroupHostName]
FROM dbo.MerchantGroup AS mg
INNER JOIN dbo.Merchant AS parent ON parent.MerchantId = mg.ParentMerchantId
INNER JOIN dbo.HttpHostName AS groupHost ON groupHost.MerchantID = parent.MerchantId AND groupHost.Priority = 0
) mGroup ON mGroup.MerchantGroupId = m.MerchantGroupId
LEFT JOIN (
SELECT po.PatronId, MAX(po.OrderDateTime) [LastOrder]
FROM dbo.PatronsOrder AS po
GROUP BY po.PatronId
) orders ON orders.PatronId = p.PatronId
INNER JOIN dbo.HttpHostName AS hhn ON hhn.MerchantID = m.MerchantId AND hhn.Priority = 1
WHERE ul.UserLoginId NOT IN (1,2,100,372) AND ul.UserStatus <> 'D' AND (
ISNULL(orders.LastOrder, '2000-01-01') > '2020-01-01' OR ul.RegistrationDate > '2022-01-01'
)
GROUP BY ul.UserLoginId, ul.FullName, ul.EmailAddress, ul.Mobile
HAVING COUNT(m.MerchantId) > 1
Methods I have tried include adding the merchant name to a group by and displaying the count of the customers, however this does not work as I cannot have anything related to the Merchant in the GROUP BY, or I wouldn't be able to use HAVING clause to identify the customers that have been to multiple merchants. I have also tried selecting all the merchants and counting the distinct customers which doesn't work as it takes into account all the customers, not specifically the customers that have been to multiple merchants only.
after running an sql
SELECT
m.stdClassID,
m.Percentage,
sc.ClassID,
sc.Form,
sc.FormName,
sc.Year,
sc.stdName
FROM stdremark m
INNER JOIN (
SELECT
sc.ClassID,
c.Form,
c.FormName,
sc.stdClassID,
c.Year,
CONCAT(s.StdFname,' ',s.StdLname) as stdName
FROM tblstdclass sc
INNER JOIN tblclass c
ON sc.ClassID=c.ClassID
INNER JOIN tblstudents s
ON sc.StdID = s.StdID
WHERE c.Year=2018
) sc ON m.stdClassID=sc.stdClassID
WHERE m.Term=3`
I come up with this result
I want to get the maximum percentage of each student grouped by the Form column
when I try to get Max() and group by()
from the sql:
SELECT
m.stdClassID,
MAX(m.Percentage),
sc.ClassID,
sc.Form,
sc.FormName,
sc.Year,
sc.stdName
FROM stdremark m
INNER JOIN (
SELECT
sc.ClassID,
c.Form,
c.FormName,
sc.stdClassID,
c.Year,
CONCAT(s.StdFname,' ',s.StdLname) as stdName
FROM tblstdclass sc
INNER JOIN tblclass c
ON sc.ClassID=c.ClassID
INNER JOIN tblstudents s
ON sc.StdID = s.StdID
WHERE c.Year=2018
) sc ON m.stdClassID=sc.stdClassID
WHERE m.Term=3
GROUP BY sc.Form`
the expected result should have been
17 71 28 upper Science 2018 Jerry Maguire
Could be an issue with MySQL allowing partial grouping. Try to extend your GROUP BY expression to group on all columns, except m.Percentage.
...
GROUP BY m.stdClassID,
sc.ClassID,
sc.Form,
sc.FormName,
sc.Year,
sc.stdName
Other DBMS would force you to do so anyway.
I have query like this ::
SELECT account.AccountNumber, account.NAME, Sum(agro.price * agro.qty) AS Expr1
FROM ((account
INNER JOIN data ON account.AccountNumber = data.acno)
INNER JOIN agro ON agro.BillNo = data.BillNo)
WHERE data.db='true'
GROUP BY account.AccountNumber, account.NAME;
I want to deduct another groupby query output in to Sum(agro.price * agro.qty) this
the another group by query is SELECT Sum(rs),acno
FROM jma group by acno;
i want to deduct Sum(agro.price * agro.qty)-Sum(rs) how its work please help me solve this
If I am understanding you correctly the following query may work for you:
SELECT subQ.AccountNumber, subQ.NAME, (subQ.subSum - jmaSum.jSum) AS FinalSum
FROM
(
SELECT a.AccountNumber, a.NAME, Sum(ag.price * ag.qty) AS subSum
FROM (account AS a
INNER JOIN data AS d ON a.AccountNumber = d.acno)
INNER JOIN agro AS ag ON ag.BillNo = d.BillNo
WHERE d.db = 'true'
GROUP BY a.AccountNumber, a.NAME
) AS subQ
LEFT JOIN
(
SELECT Sum(j.rs) AS jSum, j.acno
FROM jma AS j
GROUP BY j.acno
) AS jmaSum ON subQ.AccountNumber = jmaSum.acno
Here is the database schema:
[redacted]
I'll describe what I'm doing with the query below:
Innermost query: Select all the saleIds satisfying the WHERE conditions
Middle query: Select all the productIds that were a part of the saleId
Outermost query: SUM the products.cost and select the vendors.name.
And here is the SQL query I came up with:
SELECT vendors.name AS Company
, SUM(products.cost) AS Revenue
FROM
products
INNER JOIN sold_products
ON (products.productId = sold_products.productId)
INNER JOIN vendors
ON (products.vendorId = vendors.vendorId)
WHERE sold_products.productId IN (
SELECT sold_products.productId
FROM
sold_products
WHERE sold_products.saleId IN (
SELECT sales.saleId
FROM
markets
INNER JOIN vendors
ON (markets.vendorId = vendors.vendorId)
INNER JOIN sales_campaign
ON (sales_campaign.marketId = markets.marketId)
INNER JOIN packet_headers
ON (sales_campaign.packetHeaderId = packet_headers.packetHeaderId)
INNER JOIN packet_details
ON (packet_details.packetHeaderId = packet_headers.packetHeaderId)
INNER JOIN sales
ON (sales.packetDetailsId = packet_details.packetDetailsId)
WHERE vendors.customerId=60
)
)
GROUP BY Company
ORDER BY Revenue DESC;
Any help in optimizing this?
Since you are just using inner joins you normally simplify the query to smth like this:
SELECT ve.name AS Company
, SUM(pr.cost) AS Revenue
FROM products pr
, sold_products sp
, vendors ve
, markets ma
, sales_campaign sc
, packet_headers ph
, packet_details pd
, sales sa
Where pr.productId = sp.productId
And pr.vendorId = ve.vendorId
And ve.vendorId = ma.vendorId
And sc.marketId = ma.marketId
And sc.packetHeaderId = ph.packetHeaderId
And pd.packetHeaderId = ph.packetHeaderId)
And sa.packetDetailsId = pd.packetDetailsId
And ve.customerId = 60
GROUP BY ve.Company
ORDER BY pr.Revenue DESC;
Please try if this works and if it is faster and let me know.
I'm trying to combine the results of two queries. I'm not very proficient in mysql so I'm here for some help.
The first query is as follows:
select count(roomtypeid) as bookedrooms, day
from event_guest_hotel
where hotelid = 1 and roomtypeid = 1
group by day;
This returns:
The second query:
SELECT ehr.reservationid, ehr.day, h.name AS hotelname,
ehr.totalrooms as requested_rooms, r.name AS roomname
FROM event_hotel_reservation ehr
INNER JOIN hotel_room_type r
ON ehr.roomtypeid = r.roomtypeid
INNER JOIN hotel h
ON ehr.hotelid = h.hotelid
WHERE totalRooms != 0
AND reservationID = '1'
This returns:
Can I combine the first query with the second one, so I get the results of the first one in another resultcolumn next to 'roomname'? That way I know how many rooms are already booked and how many were originally requested from one single query.
Try:
SELECT ehr.reservationid, ehr.day, h.name AS hotelname,
ehr.totalrooms as requested_rooms, r.name AS roomname,
egh.bookedrooms
FROM event_hotel_reservation ehr
INNER JOIN hotel_room_type r ON ehr.roomtypeid = r.roomtypeid
INNER JOIN hotel h ON ehr.hotelid = h.hotelid
left outer join (
select hotelid, count(roomtypeid) as bookedrooms, day
from event_guest_hotel
where roomtypeid = 1
group by hotelid, day
) egh on h.hotelid = egh.hotelid and ehr.day = egh.day
WHERE totalRooms != 0
AND reservationID = '1'