Jump to content

Recommended Posts

Hi all,

 

I'm sure I'm missing something quite simple here.

 

Basically, I have three tables. One for employees, one for dayshifts and one for nightshifts.

 

The structure is as follows:

 

employees - employeeID, employeename

weeks - weekID

dayshifts - dayshiftID, dayshiftemployeeID, dayshiftweekid

nightshifts - nightshiftID, nightshiftemployeeID, nightshiftweekid

 

I want to find a way to find out how many different employees I've used throughout a week.

 

I can easily do this for just dayshifts or just nightshifts, using the following code:

 

$get_employees_used = mysql_query("SELECT
COUNT(DISTINCT DayShiftEmployeeID) as total
FROM dayshifts 
WHERE DayShiftWeekID = $weekid
",$connection)

 

However, I can't find a way to combine both dayshifts and nightshifts together and return the number of employees I've used across all shifts in the the week.

 

Does anyone have any ideas?

Link to comment
https://forums.phpfreaks.com/topic/274917-count-distinct-problems/
Share on other sites

I'd put them in a single table with a day/night field.

 

But until then

 

SELECT weekID, COUNT(DISTINCT empID) as employees
FROM
   (
   SELECT dayshiftweekid as weekID, dayshiftemployeeID as empID
   FROM dayshifts
   UNION
   SELECT nightshiftweekid as weekID, nightshiftemployeeID as empID
   FROM nightshifts
   )
GROUP BY weekID

Sorry, the subquery needs a table alias

 


SELECT weekID, COUNT(DISTINCT empID) as employees
FROM
       (
       SELECT dayshiftweekid as weekID, dayshiftemployeeID as empID
       FROM dayshifts
       UNION
       SELECT nightshiftweekid as weekID, nightshiftemployeeID as empID
       FROM nightshifts
       ) as shifts
GROUP BY weekID

I second Brand's suggestion to use one table for the shifts and adding a new column to identify day vs. night. The above query may get you though the current problem, but you are only creating more headaches for yourself if you don't fix it now.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.