I'm trying obtain one tabla of cars which have three rows in relations with other three columns (make, model and group) and I only want obtain one car by model.
Here a image of MySQL table:
You will see three rows with same model_id (model_id is foreign key the other table, the other table is called models)
My SQL query for obtain those cars are:
SELECT *
FROM gm_cars AS cars
INNER JOIN gm_cars_makes AS makes
ON (cars.make_id = makes.make_id)
INNER JOIN gm_cars_models AS models
ON (cars.model_id = models.model_id)
INNER JOIN gm_cars_groups AS groups
ON (cars.group_id = groups.group_id) AND
makes.make_visible = 1
ORDER BY cars.model_id;
but I wish obtain one row for one model, here one example (I have used Photoshop):
Some like: SELECT *, DISTINCT(model_id) FROM cars
If you still want to return all columns, you can create sub-query to return only one Car per Model and then write you query as before:
SELECT * FROM gm_cars AS cars
INNER JOIN (SELECT model_id, MAX(car_Id) AS car_Id FROM gm_cars GROUP BY model_id) AS grp_cars ON grp_cars.car_Id = cars.car_Id
INNER JOIN gm_cars_makes AS makes ON (cars.make_id = makes.make_id)
INNER JOIN gm_cars_models AS models ON (cars.model_id = models.model_id)
INNER JOIN gm_cars_groups AS groups ON (cars.group_id = groups.group_id) AND makes.make_visible = 1 ORDER BY cars.model_id;
You can also add GROUP BY in you main query, and add aggregation function to all other columns. But it can return you columns from different cars with the same model:
SELECT cars.model_id,
MAX(car_passengers),
MAX(car_suitcases),
....
FROM gm_cars AS cars
INNER JOIN (SELECT model_id, MAX(car_Id) AS car_Id FROM gm_cars GROUP BY model_id) AS grp_cars ON grp_cars.car_Id = cars.car_Id
INNER JOIN gm_cars_makes AS makes ON (cars.make_id = makes.make_id)
INNER JOIN gm_cars_models AS models ON (cars.model_id = models.model_id)
INNER JOIN gm_cars_groups AS groups ON (cars.group_id = groups.group_id) AND makes.make_visible = 1
GROUP BY cars.model_id
ORDER BY cars.model_id;
SELECT *
FROM gm_cars AS cars
INNER JOIN gm_cars_makes AS makes ON (cars.make_id = makes.make_id)
INNER JOIN gm_cars_models AS models ON (cars.model_id = models.model_id)
INNER JOIN gm_cars_groups AS groups ON (cars.group_id = groups.group_id)
AND makes.make_visible = 1
group by (model_id)
ORDER BY cars.model_id
is this helpful?
;with cte
AS
(
Select *,row_number() OVER(partition by model_id order by car id) rn from gm_cars
)
select * from cte where rn=1
Related
I'm working on a query in Access, but I'm really struggling to return a count of unique rows, and similarly a sum of unique values.
My query is as follows:
SELECT SiteOrders.CustomerID, Count(SiteOrders.ID) AS CountOfID, Sum(SiteOrders.Total) AS SumOfTotal, Sum(SiteOrderItems.Total) AS BrandTotal, Sum(SiteOrderItems.Quantity) AS SumOfQuantity
FROM SiteProducts INNER JOIN (SiteOrderItems INNER JOIN SiteOrders ON SiteOrderItems.OrderID = SiteOrders.ID) ON SiteProducts.ID = SiteOrderItems.ProductID
WHERE (((SiteProducts.Brand)="1") AND ((SiteOrders.OrderDate)>#4/1/2017# And (SiteOrders.OrderDate)<#4/1/2020#) AND ((SiteOrders.Paid)=True))
GROUP BY SiteOrders.CustomerID
ORDER BY SiteOrders.CustomerID;
The two fields where I want distinct values are a count on SiteOrders.ID and a sum on SiteOrders.Total.
Many thanks
Need nested query for aggregation of SiteOrders. Consider:
SELECT SiteOrders.CustomerID, Sum(SiteOrderItems.Quantity) AS SumQuantity,
Sum(SiteOrderItems.Total) AS SumTotal, Query1.CountOrderID, Query1.SumOrderTotal
FROM (SELECT CustomerID, Count(ID) AS CountOrderID, Sum(Total) AS SumOrderTotal
FROM SiteOrders
WHERE (((OrderDate) Between #4/1/2017# And #3/31/2020#) AND ((Paid)=True))
GROUP BY CustomerID) AS Query1
INNER JOIN (SiteOrders INNER JOIN (SiteProducts INNER JOIN SiteOrderItems
ON SiteProducts.ID = SiteOrderItems.ProductID)
ON SiteOrders.ID = SiteOrderItems.OrderID)
ON Query1.CustomerID = SiteOrders.CustomerID
GROUP BY SiteOrders.CustomerID, Query1.CountOrderID, Query1.SumOrderTotal;
I have a table that looks like this:
For each COMPANY there are multiple NATURAL_PERSON_ID, every NATURAL_PERSON have a date in which an audit was performed FECHA_DE_REPORTE and as a company there is a date in which the first loan was give to that company.
What I want is to select for each NATURAL_PERSON all the FOLIO_CONSULTA whose FECHA_DE_REPORTE is less or equal to FIRST_LOAN (the date in which the first loan was given for that company) Then I need to find the MAX date among each group and keep al the information (the whole row) for the value that fulfills all these conditions, and all this for each NATURAL_PERSON
So for this example the result I expected is all the information of the second row since this is the MAX() of FECHA_DE_REPORTE by COMPANY AND NATURAL_PERSON.
I have tried:
SELECT NPC.COMPANY_ID
,NPC.NATURAL_PERSON_ID
,NPS.DIGITAL_SIGNATURE_ID
,CDC.FOLIO_CONSULTA
,CDC.FECHA_DE_REPORTE
,FIRST_LOAN.FIRST_LOAN
,MAX(CDC.FECHA_DE_REPORTE) MAX_FOLIO_CONSUTA
FROM KONFIO.NATURAL_PERSON_COMPANY NPC
LEFT JOIN KONFIO.NATURAL_PERSON_SIGNATURE NPS ON NPS.NATURAL_PERSON_ID = NPC.NATURAL_PERSON_ID
JOIN KONFIO.CDC_RESPONSE CDC ON CDC.DIGITAL_SIGNATURE_ID= NPS.DIGITAL_SIGNATURE_ID
JOIN
(
SELECT CAPP.COMPANY_ID
,MIN(LOAN.DOCUMENTATION_DATE) FIRST_LOAN
FROM KONFIO.COMPANY_APPLICATION CAPP
JOIN KONFIO.LOAN ON LOAN.APPLICATION_ID = CAPP.APPLICATION_ID
GROUP BY CAPP.COMPANY_ID) FIRST_LOAN ON FIRST_LOAN.COMPANY_ID = NPC.COMPANY_ID
WHERE CDC.FECHA_DE_REPORTE <= FIRST_LOAN.FIRST_LOAN
AND NPC.COMPANY_ID IN (1033)
GROUP BY NPC.COMPANY_ID, NPC.NATURAL_PERSON_ID
but it retrieves the first value that finds so the FOLIO_CONSULTA does not correspond to the FOLIO_CONSULTA of the MAX() FECHA_DE_REPORTE
Any help would be appreciated
You should join the subquery for MAX(FECHA_DE_REPORTE) on table CDC_RESPONSE
SELECT NPC.COMPANY_ID
,NPC.NATURAL_PERSON_ID
,NPS.DIGITAL_SIGNATURE_ID
,CDC.FOLIO_CONSULTA
,CDC.FECHA_DE_REPORTE
,FIRST_LOAN.FIRST_LOAN
,T.MAX_FOLIO_CONSUTA
FROM KONFIO.NATURAL_PERSON_COMPANY NPC
INNER JOIN (
SELECT DIGITAL_SIGNATURE_ID
, MAX(FECHA_DE_REPORTE) MAX_FOLIO_CONSUTA
FROM KONFIO.CDC_RESPONSE
GROUP BY DIGITAL_SIGNATURE_ID
) T ON T.DIGITAL_SIGNATURE_ID = NPS.DIGITAL_SIGNATURE_ID
AND T.MAX_FOLIO_CONSUTA = CDC.FECHA_DE_REPORTE
LEFT JOIN KONFIO.NATURAL_PERSON_SIGNATURE NPS ON NPS.NATURAL_PERSON_ID = NPC.NATURAL_PERSON_ID
JOIN KONFIO.CDC_RESPONSE CDC ON CDC.DIGITAL_SIGNATURE_ID= NPS.DIGITAL_SIGNATURE_ID
JOIN
(
SELECT CAPP.COMPANY_ID
,MIN(LOAN.DOCUMENTATION_DATE) FIRST_LOAN
FROM KONFIO.COMPANY_APPLICATION CAPP
JOIN KONFIO.LOAN ON LOAN.APPLICATION_ID = CAPP.APPLICATION_ID
GROUP BY CAPP.COMPANY_ID) FIRST_LOAN ON FIRST_LOAN.COMPANY_ID = NPC.COMPANY_ID
WHERE CDC.FECHA_DE_REPORTE <= FIRST_LOAN.FIRST_LOAN
AND NPC.COMPANY_ID IN (1033)
GROUP BY NPC.COMPANY_ID, NPC.NATURAL_PERSON_ID
...... missing part
I have the following table structure:
tbl_catalogue_state
In tbl_catalogue there is a part number 58674 that has three states in the tbl_catalogue_state_lk table. Here is the result when I run a query inner joining the three tables.
As expected there are multiple rows returned.
Is there a way to only return one row having the values for each catalgue_state_id on the same row?
I would also like the ability to ignore a row for example:
select tbl_catalogue.catalogue_part, tbl_catalogue_state.catalogue_state_id from tbl_catalogue
inner join tbl_catalogue_state_lk on tbl_catalogue.catalogue_id = tbl_catalogue_state_lk.catalogue_id
inner join tbl_catalogue_state on tbl_catalogue_state_lk.catalogue_state_id = tbl_catalogue_state.catalogue_state_id
where tbl_catalogue_state_lk.catalogue_state_id <> 1;
The above select still returns two rows.
UPDATE
I was able to use GROUP_CONCAT:
select tbl_catalogue.catalogue_part, GROUP_CONCAT(tbl_catalogue_state.catalogue_state_id) as cat_state from tbl_catalogue
inner join tbl_catalogue_state_lk on tbl_catalogue.catalogue_id = tbl_catalogue_state_lk.catalogue_id
inner join tbl_catalogue_state on tbl_catalogue_state_lk.catalogue_state_id = tbl_catalogue_state.catalogue_state_id
where tbl_catalogue_state_lk.catalogue_state_id <> 1
group by tbl_catalogue.catalogue_id;
My issue is the above statement still returns a row. I need it to return nothing.
I was able to use not exists:
select tc.catalogue_part, GROUP_CONCAT(tcs.catalogue_state_id) as cat_state from tbl_catalogue as tc
inner join tbl_catalogue_state_lk as tcsl on tc.catalogue_id = tcsl.catalogue_id
inner join tbl_catalogue_state as tcs on tcsl.catalogue_state_id = tcs.catalogue_state_id
where
not exists
(
select tcsl2.catalogue_state_id from tbl_catalogue_state_lk as tcsl2
where tcsl2.catalogue_state_id = 6 and tcsl2.catalogue_id = tc.catalogue_id
)
and
not exists
(
select tcsl3.catalogue_state_id from tbl_catalogue_state_lk as tcsl3
where tcsl3.catalogue_state_id = 1 and tcsl3.catalogue_id = tc.catalogue_id
)
and
not exists
(
select tcsl3.catalogue_state_id from tbl_catalogue_state_lk as tcsl3
where tcsl3.catalogue_state_id = 2 and tcsl3.catalogue_id = tc.catalogue_id
)
group by tc.catalogue_id;
Is there a way that I can combine these two queries:
FIRST QUERY
select top 100
WORK.pzInsKey,
WORK.pyID,
PARTY.MacID,
PARTY.OtherPartyID,
PARTY.CustomerEmail,
ACCOUNT.AccountNumber,
ACCOUNT.AccountName,
ACCOUNT.AdviserCode,
ACCOUNT.AdviserName,
ACCOUNT.DealerCode,
ACCOUNT.DealerName,
ACCOUNT.PrimaryAccount,
ACCOUNT.ProductCategory,
ACCOUNT.ProductCode,
ACCOUNT.ProductDescription,
ACCOUNT.RegisteredState,
DOCUMENT.UDOCID
from
workTable WORK,
partyTable PARTY,
accountTable ACCOUNT,
documentTable DOCUMENT,
notesTable NOTES
where WORK.pzInsKey = PARTY.pxInsIndexedKey
and WORK.pzInsKey = ACCOUNT.pxInsIndexedKey
and WORK.pyID = DOCUMENT.CaseID
and SECOND QUERY
SELECT top 100
BusinessAreaTbl.businessarea,
ProcessTbl.process,
SubProcessTbl.subprocess
FROM workTable WORK
LEFT OUTER JOIN (SELECT DISTINCT Product_ID businessarea_id, Product businessarea from CaseTypesTable) BusinessAreaTbl
ON WORK.RequestBusinessArea#1 = BusinessAreaTbl.businessarea_id
LEFT OUTER JOIN (SELECT DISTINCT Process_ID, Process, Product_ID businessarea_id from CaseTypesTable) ProcessTbl
ON WORK.RequestProcess#1 = ProcessTbl.process_id
AND ProcessTbl.businessarea_id = WORK.RequestBusinessArea#1
LEFT OUTER JOIN (SELECT DISTINCT SubProcess_ID, SubProcess, Product_ID businessarea_id, Process_ID from CaseTypesTable) SubProcessTbl
ON WORK.RequestSubProcess#1 = SubProcessTbl.subprocess_id
AND SubProcessTbl.businessarea_id = WORK.RequestBusinessArea#1
AND SubProcessTbl.process_id = WORK.RequestProcess#1
It's basically two queries which produce separate results, but each query includes data from the workTable. In the 2nd query, the workTable data is derived from the CaseTypesTable.
I essentially just want the businessarea, process, and subprocess fields to be included with the results of the first query.
Thanks in advance for any help.
This should work:
(SELECT top 100
w.pzInsKey,
w.pyID,
p.MacID,
p.OtherPartyID,
p.CustomerEmail,
a.AccountNumber,
a.AccountName,
a.AdviserCode,
a.AdviserName,
a.DealerCode,
a.DealerName,
a.PrimaryAccount,
a.ProductCategory,
a.ProductCode,
a.ProductDescription,
a.RegisteredState,
d.UDOCID
FROM workTable w
LEFT JOIN partyTable p
ON w.pzInsKey = p.pxInsIndexedKey
LEFT JOIN accountTable a
ON w.pzInsKey = a.pxInsIndexedKey
LEFT JOIN documentTable d
ON w.pyID = d.CaseID)
UNION
(SELECT top 100
ba.businessarea,
pr.process,
spr.subprocess
FROM workTable w
LEFT OUTER JOIN (SELECT DISTINCT Product_ID businessarea_id, Product businessarea from CaseTypesTable) BusinessAreaTbl ba
ON w.RequestBusinessArea#1 = ba.businessarea_id
LEFT OUTER JOIN (SELECT DISTINCT Process_ID, Process, Product_ID businessarea_id from CaseTypesTable) ProcessTbl pr
ON w.RequestProcess#1 = pr.process_id
AND pr.businessarea_id = w.RequestBusinessArea#1
LEFT OUTER JOIN (SELECT DISTINCT SubProcess_ID, SubProcess, Product_ID businessarea_id, Process_ID from CaseTypesTable) SubProcessTbl spr
ON w.RequestSubProcess#1 = spr.subprocess_id
AND spr.businessarea_id = w.RequestBusinessArea#1
AND spr.process_id = w.RequestProcess#1))
Use the keyword UNION to combine two or more seperate SELECT statements.
To begin with I have 4 tables I am dealing with.
I have a classes table that is a 1->N relationship with a sections table which also has a 1->N relationship with a lessons table.
So to put it in perpective:
Classes
Sections
Lessons
The last table is an activityLog, when the student accesses a lesson this is recorded using the following:
ActivityLog Row -> actorID (user ID), classID, sectionID, lessonID
I want to pull out the last 5 unique lessons the student has visited. I tried using both DISTINCT and GROUP BY without success.
The same records are being returned each time, not the latest classes that they have visited.
Using GROUP BY
SELECT activityLog.actorID, activityLog.activityDate,
strClasses.classID, strClasses.className,
strSections.sectionID, strSections.sectionName,
strLessons.lessonID, strLessons.lessonName
FROM activityLog
LEFT JOIN strClasses ON strClasses.classID = activityLog.classID
LEFT JOIN strSections ON strSections.sectionID = activityLog.sectionID
LEFT JOIN strLessons ON strLessons.lessonID = activityLog.lessonID
WHERE activityLog.activityTypeID = 6 AND activityLog.actorID = 3
GROUP BY activityLog.lessonID
ORDER BY activityLog.activityDate DESC
LIMIT 5
Using DISTINCT
SELECT DISTINCT activityLog.actorID,
strClasses.classID, strClasses.className,
strSections.sectionID, strSections.sectionName,
strLessons.lessonID, strLessons.lessonName
FROM activityLog
LEFT JOIN strClasses ON strClasses.classID = activityLog.classID
LEFT JOIN strSections ON strSections.sectionID = activityLog.sectionID
LEFT JOIN strLessons ON strLessons.lessonID = activityLog.lessonID
WHERE activityLog.activityTypeID = 6 AND activityLog.actorID = 3
ORDER BY activityLog.activityDate DESC
LIMIT 5
I cannot figure out why the latest records are not being displayed.
Based on your change, how does this suit you?
SELECT activityLog.actorID, activityLog.activityDate,
strClasses.classID, strClasses.className,
strSections.sectionID, strSections.sectionName,
strLessons.lessonID, strLessons.lessonName
FROM activityLog
LEFT JOIN strClasses ON strClasses.classID = activityLog.classID
LEFT JOIN strSections ON strSections.sectionID = activityLog.sectionID
LEFT JOIN strLessons ON strLessons.lessonID = activityLog.lessonID
WHERE activityLog.activityTypeID = 6 AND activityLog.actorID = 3
AND activityLog.activityDate = (SELECT MAX(activityDate) FROM activityLog AS lookup WHERE lessonID = activityLog.lessonID)
ORDER BY activityLog.activityDate DESC
LIMIT 5
Based on your description, I'm not sure why you're using LEFT JOIN, but I've left it in just in case.
Try group by like below
GROUP BY activityLog.classID,activityLog.sectionID,activityLog.lessonID
I think it will work, or just sent me create scripts for these I will create that query
Well, there's got to be a datetime in the ActivityLog I hope... so Try this:
Select s.Name, c.ClassName
From Students s
left Join On Classes c
On c.ClassId In
(Select Distinct ClassId From Classes
Where (Select Count(Distinct ClassId) From Classes ic
Join ActivityLog l On l.UserId = s.UserId
And l.ClassId = c.ClassId
Where classId = c.ClassId
And activityDateTime > l.activityDateTime)
< 5)