I have a field that contains the date that a client was placed into a job. There are multiple placements for each client, and I would like to calculate the number of days between the first and last placements for each client.
If I remeber right this is a little more tricky than you would think. I think you might get an error message if you don't use a temp table. I found this code, which is similar to what you want.
SELECT COUNT(user_id)
FROM (SELECT user_id, MAX(TableDate) MaxUserDate
FROM board
GROUP BY user_id) TempTable
WHERE DATEDIFF(day, MaxUserDate, getdate()) <= 30
Hi Dodge20,
Thanks for the fast reply. I have to admit that I am just learning SQL, so I could use a little explanation, please. I am trying to calculate the difference between the MAX and MIN for a date field.
Where does the MIN date fit into your query?:
SELECT COUNT(user_id)
FROM (SELECT user_id, MAX(TableDate) MaxUserDate
FROM board
GROUP BY user_id) TempTable
WHERE DATEDIFF(day, MaxUserDate, getdate()) <= 30
SELECT COUNT(user_id)
FROM (SELECT user_id, MAX(TableDate) MaxUserDate, Min(TableDate) MinUserDate
FROM board
GROUP BY user_id) TempTable
WHERE DATEDIFF(day, MaxUserDate, MinUserDate)
When I run this query:
SELECT COUNT(tblClient.ClientID)
FROM (SELECT (tblClient.ClientID), MAX(tblJobPlacement.PlacementDate) MaxUserDate, Min(tblJobPlacement.PlacementDate) MinUserDate
FROM board
GROUP BY user_id) TempTable
WHERE DATEDIFF(day, MaxUserDate, MinUserDate);
I get this message:
Syntax error (missing operator) in query expression
'MAX(tblJobPlacement.PlacementDate) MaxUserDate'
I wasn't aware you were pulling from 2 tables. Your query will change quite a bit then. You will have to join the 2 tables together. Maybe you don't need info from the 2 tables. I think you are just using userid because that is what I used in my example. Try just changing tblClient.clientID to a field in the tblJobPlacement table.
Also board was the name of the table I used you will want to change it to tblJobPlacement.
SELECT COUNT(examplefield)
FROM (SELECT examplefield, MAX(tblJobPlacement.PlacementDate) MaxUserDate, Min(tblJobPlacement.PlacementDate) MinUserDate
FROM tblJobPlacement
GROUP BY user_id) TempTable
WHERE DATEDIFF(day, MaxUserDate, MinUserDate);
SELECT COUNT(examplefield)
FROM (SELECT examplefield, MAX(PlacementDate) AS MaxUserDate, Min(PlacementDate) AS MinUserDate
FROM tblJobPlacement
GROUP BY examplefield) tblJobPlacement
WHERE DATEDIFF(day, MaxUserDate, MinUserDate);
Ok, thanks for the help guys. You definitely got me in the right direction. Here is what ended up working for me:
SELECT tblJobPlacement.ClientID, Max([tblJobPlacement]![PlacementDate])-Min([tblJobPlacement]![PlacementDate])
FROM tblJobPlacement
GROUP BY tblJobPlacement.ClientID;
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.