SQL Count number of people that do not hold a qualification - mysql

hoping you can help me as I am going round in circles!
I need to count the number of people that do not hold a certain qualification.
I have tried NOT but this returns all the other qualifications other than the one I wish to count. Whereas I want to specifically count the number of people that do not hold the qualification, i.e. do not have a row entry in the table.
SELECT COUNT(tmp.personnelID) AS Number,
tmp.QualificationID
FROM(SELECT pa.PersonnelID,
pq.QualificationID
FROM dbo.PersonnelActive pa
LEFT JOIN dbo.PersonnelQualifications pq ON pq.PersonnelID = pa.PersonnelID
WHERE NOT pq.QualificationID = 125) tmp
GROUP BY tmp.QualificationID
Any help you guys can give or point me in the right direction would be greatly appreciated.

You should count for personnelID that are not in the personnelID with a QualificationID = 125
SELECT COUNT(pa.personnelID) AS Num,
pq.QualificationID
FROM PersonnelActive pa
INNER JOIN dbo.PersonnelQualifications pq ON pq.PersonnelID = pa.PersonnelID
where pa.PersonnelID NOT IN ( SELECT pa.PersonnelID
FROM dbo.PersonnelActive pa
INNER JOIN dbo.PersonnelQualifications pq ON pq.PersonnelID = pa.PersonnelID
WHERE pq.QualificationID = 125
)
GROUP BY pq.QualificationID

Related

Need count of transactional table based on other tables including zeros where there are no matches

I have four tables, three of which are pretty static: haul_types, dumpster_type_team (the dumpster_type_team has the many-to-many relationship between dumpster_types and teams), and users. The fourth table, hauls, has transactional data.
haul_types:
id
name
dumpster_type_team:
id
dumpster_type_id
team_id
users:
id
first_name
last_name
is_driver
team_id
hauls:
haul_type_id
haul_status_id
set_dumpster_type_id
completed_driver_id
team_id
I would like a query that has a combination of dumpster_types, haul_types, and drivers (users) and a count of the hauls they were involved in. In some cases, there should be a count of zero because some drivers haven't completed hauls for every haul_type / dumpster type combination.
Here's the query I have so far that seems to be behaving as if it is an inner join because the records are getting filtered to only show where there are matches:
SELECT
c.haul_type_id,
c.dumpster_type_id,
c.driver_id,
count(h.id) AS haul_count
FROM
hauls h
RIGHT JOIN ( SELECT DISTINCT
ht.id AS haul_type_id,
dtt.dumpster_type_id AS dumpster_type_id,
dtt.team_id AS team_id,
u.id AS driver_id
FROM
haul_types ht
CROSS JOIN dumpster_type_team dtt
CROSS JOIN users u
WHERE
u.team_id = dtt.team_id
AND u.is_driver = TRUE) c ON c.haul_type_id = h.haul_type_id
AND c.dumpster_type_id = h.set_dumpster_type_id
AND c.driver_id = h.completed_driver_id
AND c.team_id = h.team_id
WHERE
h.team_id = 9
AND h.haul_status_id = 3
AND h.completed_driver_id IS NOT NULL
GROUP BY
c.haul_type_id, c.dumpster_type_id, c.driver_id
When I run the subquery in isolation:
SELECT DISTINCT
ht.id AS haul_type_id,
dtt.dumpster_type_id AS dumpster_type_id,
dtt.team_id AS team_id,
u.id AS driver_id
FROM
haul_types ht
CROSS JOIN dumpster_type_team dtt
CROSS JOIN users u
WHERE
u.team_id = dtt.team_id
AND u.is_driver = TRUE
I get the results I want: a row for each permutation of haul_type, dumpster_type, driver_id, and team_id. However, when I run the entire query, I get filtered results despite the right join.
What I would like to have is the following:
If I have 4 haul_types: delivery, swap, live, pickup
and 2 dumpster_types: 10YD, 15YD
and 2 drivers: 1, 2
I would like a haul count for the combination of haul_type, dumpster_type, and driver. If there are no hauls matching the row, show 0:
Any help is appreciated. Thank you
The description of the question and the query seem to have little to do with each other. I don't know what a "pivot table" is supposed to be.
I would like a query that has a combination of dumpster_types, haul_types, and drivers (users) and a count of the hauls they were involved in.
This sounds like a cross join to generate the rows and then a left join/group by to calculate the results:
select d.dumpster_id, ht.haul_type_id, d.driver_id, count(h.driver_id)
from dumpster_types d cross join
haul_types ht cross join
drivers d left join
hauls h
on h.dumpster_id = d.dumpster_id and
h.haul_type_id = ht.haul_type_id and
h.driver_id = d.driver_id
group by d.dumpster_id, ht.haul_type_id, d.driver_id;
Running the query #GordonLinoff provided, exposed the issue I was facing - when applying a where clause on the top level query, the results were getting filtered to only matches. I moved the where clause to individual subqueries and now I am getting all expected results.
Not sure if this is the most efficient way to write it but it yields the correct results:
SELECT
d.dumpster_type_id,
ht.id AS haul_type_id,
u.id AS driver_id,
count(h.id) AS haul_count
FROM (
SELECT
dumpster_type_id,
team_id
FROM
dumpster_type_team
WHERE
team_id = 9) d
CROSS JOIN haul_types ht
CROSS JOIN (
SELECT
users.id
FROM
users
WHERE
users.is_driver = TRUE
AND users.team_id = 9) u
LEFT JOIN (
SELECT
id, set_dumpster_type_id, haul_type_id, completed_driver_id, team_id
FROM
hauls
WHERE
haul_status_id = 3
AND team_id = 9) h ON h.set_dumpster_type_id = d.dumpster_type_id
AND h.haul_type_id = ht.id
AND h.completed_driver_id = u.id
AND h.team_id = d.team_id
GROUP BY
d.dumpster_type_id,
ht.id,
u.id

SQL Statement - Too dumb to figure it out

I have a working knowledge of SQL Server along with the ability to perform most basic queries. However, I'm stuck and needs some help with this one. I have 6 related tables from which I need to derive a set of data.
Tables are as follows:
MTMeterReadings mr
Actual
GroupID
MeterID
CreateDate
MTMeterReadingGroups mg
MeterReadingGroupID
MeterSourceID
EquipmentID
MTMeterSources ms
MeterSourceID
Description
MTMeters m
MeterID
Description
SCEquipment eq
EquipmentID
CustomerID
ARCustomers c
CustomerID
CustomerName
My desired result set is to show the following data for each Actual record in the MTMeterReadins table where mr.CreateDate > 'mm/dd/yyy':
mr.actual | mr.CreateDate | ms.description | e.EquipmentID | c.CustomerName
So far, I've been able to create a query with everything I need except c.CustomerName, but just can't seem to take it all the way (I can be JOIN challenged at times).
Any help with this is greatly appreciated.
I apologize, but I didn't know if the query I already had would be helpful or not.
Here is what I have that yields everything I want except customer name:
SELECT
mg.EquipmentID,
CAST(mr.Actual AS decimal(12, 0)) AS Meter,
CAST(mr.CreateDate AS DATE) AS MeterDate,
ms.MeterSource, m.Description
FROM
MTMeterReadings AS mr
INNER JOIN
MTMeterReadingGroups AS mg ON mr.MeterReadingGroupID = mg.MeterReadingGroupID
INNER JOIN
MTMeterSources AS ms ON mg.MeterSourceID = ms.MeterSourceID
INNER JOIN
MTMeters AS m ON mr.MeterID = m.MeterID
WHERE
(mr.CreateDate >= '01/01/2014') AND (mr.CreateDate <= '02/20/2015')
ORDER BY
MeterDate DESC, mg.EquipmentID, m.Description
However, every attempt that I have made to add CustomerName yields a multiple of the records that I have in the mr table. I can't tell exactly what my error is, but I'm assuming it is an incorrect join. Maybe simple for someone with a bigger SQL brain than me, but this is far from being inside my core knowledge base as I learned SQL from a SAMS "Teach Yourself SQL in 10 Minutes" book.
You are missing additional 2 joins:
SELECT mg.EquipmentID, CAST(mr.Actual AS decimal(12, 0)) AS Meter, CAST(mr.CreateDate AS DATE) AS MeterDate, ms.MeterSource, m.Description, ar.CustomerName
FROM MTMeterReadings AS mr INNER JOIN
MTMeterReadingGroups AS mg ON mr.MeterReadingGroupID = mg.MeterReadingGroupID INNER JOIN
MTMeterSources AS ms ON mg.MeterSourceID = ms.MeterSourceID INNER JOIN
MTMeters AS m ON mr.MeterID = m.MeterID
INNER JOIN SCEquipment eq on mg.EquipmentID = eq.EquipmentID
INNER JOIN ARCustomers ar on eq.CustomerID = ar.CustomerID
WHERE (mr.CreateDate >= '01/01/2014') AND (mr.CreateDate <= '02/20/2015')
ORDER BY MeterDate DESC, mg.EquipmentID, m.Description
It should be as simple as this:
SELECT mg.EquipmentID,
CAST(mr.Actual AS DECIMAL(12, 0)) AS Meter,
CAST(mr.CreateDate AS DATE) AS MeterDate,
ms.MeterSource,
m.Description
c.CustomerName
FROM MTMeterReadings AS mr INNER JOIN
MTMeterReadingGroups AS mg ON mr.MeterReadingGroupID = mg.MeterReadingGroupID INNER JOIN
MTMeterSources AS ms ON mg.MeterSourceID = ms.MeterSourceID INNER JOIN
MTMeters AS m ON mr.MeterID = m.MeterID INNER JOIN
SCEquipment AS e ON mg.EquipmentID = e.EquipmentID INNER JOIN
ARCustomers AS c ON e.CustomerID = c.CustomerID
WHERE (mr.CreateDate BETWEEN '01/01/2014' AND '02/20/2015')
ORDER BY MeterDate DESC,
mg.EquipmentID,
m.Description
But that's assuming that there are no possible outer joins and that every relation you want has at least one record.
Also, note that if mr.CreateDate is a datetime you will miss times on 2/20/2015 after midnight.

Issues with a MySQL JOIN statement

i have 5 tables called personal,dailypay,bonuses,iou and loans am trying to write a query that will generate payroll from this table's...my code is
select personal.name as NAME,
(sum(dailypay.pay) + bonuses) - (iou.amount + loans.monthly_due)) as SALARY
from personal
join dailypay on personal.eid = dailypay.eid
left join bonuses on personal.eid = bonuses.eid
left join iou on personal.eid = iou.eid
left join where dailypay.date = 'specified_date'
and bonuses.date_approved = 'specified_date'
and iou.date_approved = 'specified_date'
and loans.date = month(now()
It returns the name and null salary values for staffs that does have records for either bonuses,iou and loans. But i want to sum their dailypay, deduct/add deductions or additions return the values, in the event of no record it should proceed with the summation without any deduction or subtraction.
You missed something when pasting the code, as there is no join for the loans table. Also, you are using the table bonuses as a value, you need a field name also. I added some code for the join and for the field, but used ??? for names that are unknown to me.
When you add or subtract a null value to something else, the result is null, that's why you get null as result when any of the values from the left-joined tables are missing. You can use ifnull(..., 0) to turn a null value into zero.
You need a group by clause, otherwise it would sum up the salary for all persons.
If I get you right, you have several records in the dailypay table for each user, but only one record per user in the other tables? In that case you have the problem that you will be joining the other tables against each row in the dailypay, so if you have 20 payment records for a user, it will count the bonus 20 times. You can use an aggregate like max to get the value only once.
You have put conditions for the left.joined tables in the where clause, but this will turn the joins into inner joins. You should have those conditions in each join clause.
select
personal.name as NAME,
(sum(dailypay.pay) + ifnull(max(bonuses.???), 0)) - (ifnull(max(iou.amount), 0) + ifnull(max(loans.monthly_due), 0)) as SALARY
from
personal
inner join dailypay on personal.eid = dailypay.eid
left join bonuses on personal.eid = bonuses.eid and bonuses.date_approved = 'specified_date'
left join iou on personal.eid = iou.eid and iou.date_approved = 'specified_date'
left join loans on personal.??? = loans.??? and loans.date = month(now())
where
dailypay.date = 'specified_date'
group by
personal.name
There seems to be an extranous left join before the where and a missing closing bracket ) in month(now()
so it should look like:
select personal.name as NAME,
(sum(dailypay.pay) + bonuses) - (iou.amount + loans.monthly_due)) as SALARY
from personal
join dailypay on personal.eid = dailypay.eid
left join bonuses on personal.eid = bonuses.eid
left join iou on personal.eid = iou.eid
where dailypay.date = 'specified_date'
and bonuses.date_approved = 'specified_date'
and iou.date_approved = 'specified_date'
and loans.date = month(now())

SQL: Get latest entries from history table

I have 3 tables
person (id, name)
area (id, number)
history (id, person_id, area_id, type, datetime)
In this tables I store the info which person had which area at a specific time. It is like a salesman travels in an area for a while and then he gets another area. He can also have multiple areas at a time.
history type = 'I' for CheckIn or 'O' for Checkout.
Example:
id person_id area_id type datetime
1 2 5 'O' '2011-12-01'
2 2 5 'I' '2011-12-31'
A person started traveling in area 5 at 2011-12-01 and gave it back on 2011-12-31.
Now I want to have a list of all the areas all persons have right now.
person1.name, area1.number, area2.number, area6.name
person2.name, area5.number, area9.number
....
The output could be like this too (it doesn't matter):
person1.name, area1.number
person1.name, area2.number
person1.name, area6.number
person2.name, area5.number
....
How can I do that?
This question is, indeed, quite tricky. You need a list of the entries in history where, for a given user and area, there is an 'O' record with no subsequent 'I' record. Working with just the history table, that translates to:
SELECT ho.person_id, ho.area_id, ho.type, MAX(ho.datetime)
FROM History AS ho
WHERE ho.type = 'O'
AND NOT EXISTS(SELECT *
FROM History AS hi
WHERE hi.person_id = ho.person_id
AND hi.area_id = ho.area_id
AND hi.type = 'I'
AND hi.datetime > ho.datetime
)
GROUP BY ho.person_id, ho.area_id, ho.type;
Then, since you're really only after the person's name and the area's number (though why the area number can't be the same as its ID I am not sure), you need to adapt slightly, joining with the extra two tables:
SELECT p.name, a.number
FROM History AS ho
JOIN Person AS p ON ho.person_id = p.id
JOIN Area AS a ON ho.area_id = a.id
WHERE ho.type = 'O'
AND NOT EXISTS(SELECT *
FROM History AS hi
WHERE hi.person_id = ho.person_id
AND hi.area_id = ho.area_id
AND hi.type = 'I'
AND hi.datetime > ho.datetime
);
The NOT EXISTS clause is a correlated sub-query; that tends to be inefficient. You might be able to recast it as a LEFT OUTER JOIN with appropriate join and filter conditions:
SELECT p.name, a.number
FROM History AS ho
JOIN Person AS p ON ho.person_id = p.id
JOIN Area AS a ON ho.area_id = a.id
LEFT OUTER JOIN History AS hi
ON hi.person_id = ho.person_id
AND hi.area_id = ho.area_id
AND hi.type = 'I'
AND hi.datetime > ho.datetime
WHERE ho.type = 'O'
AND hi.person_id IS NULL;
All SQL unverified.
You're looking for results where each row may have a different number of columns? I think you may want to look into GROUP_CONCAT()
SELECT p.`id`, GROUP_CONCAT(a.`number`, ',') AS `areas` FROM `person` a LEFT JOIN `history` h ON h.`person_id` = p.`id` LEFT JOIN `area` a ON a.`id` = h.`area_id`
I haven't tested this query, but I have used group concat in similar ways before. Naturally, you will want to tailor this to fit your needs. Of course, group concat will return a string so it will require post processing to use the data.
EDIT I thikn your question has been edited since I began responding. My query does not really fit your request anymore...
Try this:
select *
from person p
inner join history h on h.person_id = p.id
left outer join history h2 on h2.person_id = p.id and h2.area_id = h.area_id and h2.type = 'O'
inner join areas on a.id = h.area_id
where h2.person_id is null and h.type = 'I'

MySQL SELECT DISTINCT ORDER BY problem

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)