473,651 Members | 2,765 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sql query one to many count

374 Contributor
Hi people, Im struggling with this quite hard to explain database query.

How would I count only once the (many) occurance of a record within a one to many relationship.

I have the following tables:

tblCheck:

lTableID
StaffNumber
CheckCompletedD ate


tblError:

lCheckID
StaffNumber
ErrorType


The bold ID's show the link between the tables. I have a sql string that will count the number of times checks have been carried out between current date and CheckCompletedD ate-30days for a staffnumber.

I then however, want to count whether this check resulted in an error. At present I can count the number of times an error occured but sometimes this can be more than once for a single Check. I want a simple yes/no count was there an error or not.

I will then be grouping this by StaffNumber.

So my output would be:
From current date to date-30days:

StaffNumber // ChecksCarriedOu t
100010134 // 4
234234212 / / 1

---------

StaffNumber // Errorfoundinche ck?
100010134 // 2
234234212 // 0


This will show how many checks had been carried out on different pieces of a staffs work and how many times a piece of work was wrong (not how many errors were within this as a result of the check, just simply if the work was right or wrong).

Using the above examples 4 seperate pieces of work were checked and 2 of these contained errors (the number of errors i dont care about, but my tblErrors shows all of these errors, i just want to know if a check resulted in an error).

I will then be able to calculate a percentage for the number of pieces of work checked against the number of these that were incorrect (even if they contained 20 errors or 1 error, it would still be classed as incorrect).


The query which counts the # of checks correctly:
Expand|Select|Wrap|Line Numbers
  1.  Set Rs = Db.OpenRecordset("SELECT sStaffNumber, count(*) AS checkcount FROM tblcheck WHERE dteCheckCompletedDate BETWEEN date() AND date()-30  Group By sStaffNumber;")
The query which counts the # of errors within these checks (but this is currently the sum of every error within that check so if a case contained 10 errors it counts all 10, i want to just see it say 1 error against this check):

Expand|Select|Wrap|Line Numbers
  1.    Set Rs = Db.OpenRecordset("Select tblError.sStaffNumber, Count(*) As ErrorCount FROM TblError LEFT JOIN tblCheck ON (tblError.lCheckID = tblCheck.lTableID) Where tblCheck.dteCheckCompletedDate BETWEEN date() AND date()-30 GROUP BY tblError.sStaffNumber")
Thanks for any help sorry to go on but its hard to explain.
Feb 23 '10 #1
8 3702
aas4mis
97 New Member
Instead of using "count(*)" try using "1" (with the quotes), this will return the string "1", which could just as easily be "error".

Expand|Select|Wrap|Line Numbers
  1. Set Rs = Db.OpenRecordset("Select tblError.sStaffNumber, "1" As AtLeastOneError FROM TblError LEFT JOIN tblCheck ON (tblError.lCheckID = tblCheck.lTableID) Where tblCheck.dteCheckCompletedDate BETWEEN date() AND date()-30 GROUP BY tblError.sStaffNumber ORDER BY tblError.sStaffNumber")
This already filters out the "non error" staff members due to your join, but you probably already knew that. :)

Side note: Not sure if access automatically does the sort for you, but you may want to put an ORDER BY clause in there.. else you might get duplicate staff id's..

for example..

100010134 / 1 <-- need to fire that guy. :P
234234212 / 1
211865152 / 1
100010134 / 1 <-- need to fire that guy. :P

Hope that helped!
Feb 23 '10 #2
munkee
374 Contributor
Thanks for this aas4mis i've been teaching myself over the last week so it really got me stuck easy. I will give your code a go at work tomorrow, i'm in a strange situation where I don't actually have Access available to me. At present i'm importing the data in to excel and running queries from there from an access database file that is used by a different department so solutions aren't as easy to work out as I would have liked.

Just had a good read of the code. Would I then have to do a Count() to get the total number of times that staff member had a case appear between the dates specified?

So I basically can output on a summary sheet using your above example and saying they had 5 checks done:

Expand|Select|Wrap|Line Numbers
  1. StaffNumber #ofChecks #ofcheckswitherrors
  2. 100010134  5                 2
  3. 234234212  3                 1
  4. 211865152  10               1
Feb 23 '10 #3
patjones
931 Recognized Expert Contributor
Hi munkee -

Try this...
Expand|Select|Wrap|Line Numbers
  1. SELECT tblCheck.sStaffNumber, COUNT(tblError.sStaffNumber) AS ErrorCount 
  2. FROM tblCheck LEFT JOIN tblError ON (tblCheck.lTableID = tblError.lCheckID) 
  3. WHERE tblCheck.dteCheckCompletedDate BETWEEN date() AND date()-30 
  4. GROUP BY tblCheck.sStaffNumber, tblError.sStaffNumber

The key here is to GROUP BY on sStaffNumber in each table. I tried this query in one of my Access databases that has a similar arrangement to yours and it worked nicely.

Pat
Feb 25 '10 #4
patjones
931 Recognized Expert Contributor
munkee -

I hasten to add that for a simple Y/N entry you can modify the SELECT clause of my SQL with an IIf statement as follows...
Expand|Select|Wrap|Line Numbers
  1. SELECT tblCheck.sStaffNumber, IIf(COUNT(tblError.sStaffNumber)>0, "Y", "N") AS [Has Error(s)?] 
  2.  
One of the nice things about using SQL in an Excel or Access environment is that you can embed VBA functionality like "IIf" in the query. I hope this helps.

Pat
Feb 25 '10 #5
patjones
931 Recognized Expert Contributor
Hi again -

Sorry to be a pain, but yet another possibility for the SELECT clause is...
Expand|Select|Wrap|Line Numbers
  1. SELECT tblCheck.sStaffNumber, IIf(tblError.sStaffNumber IS NULL, "N", "Y") AS [Has Error(s)?]
  2.  
...which is merely a slight modification on the IIf formulation.

Pat
Feb 25 '10 #6
aas4mis
97 New Member
zepphead80,
Nice way to eliminate the join! Should this also have a WHERE clause now since there's no join?

munkee,
Keep an eye out for this one, I believe if you're populating a list/combobox with the results you'll have an entry for every staffNumber, even if they don't have an error.

zepphead80,
Please correct me if I'm wrong.
Feb 26 '10 #7
patjones
931 Recognized Expert Contributor
Hi -

The JOIN isn't eliminated; I was just pointing out a couple other ways to rewrite the SELECT line...everythi ng else would stay the same. Sorry for the confusion.

I inferred from munkee's original post that he wanted to show staff even if they had no errors, as in

StaffNumber // Errorfoundinche ck?

100010134 // 2
234234212 // 0

However, to eliminate those staff, the WHERE clause in my query just needs to be modified:

Expand|Select|Wrap|Line Numbers
  1. SELECT tblCheck.sStaffNumber, COUNT(tblError.sStaffNumber) AS ErrorCount 
  2. FROM tblCheck LEFT JOIN tblError ON (tblCheck.lTableID = tblError.lCheckID) 
  3. WHERE COUNT(tblError.sStaffNumber) > 0 AND tblCheck.dteCheckCompletedDate BETWEEN date() AND date()-30 
  4. GROUP BY tblCheck.sStaffNumber, tblError.sStaffNumber

Hopefully munkee can let us know whether or not this works for him.

Pat
Feb 26 '10 #8
aas4mis
97 New Member
Ah, I see.. this quick reply box works a little to "quick" for me sometimes. :)
Feb 26 '10 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

20
10132
by: | last post by:
If I need to check if a certain value does exist in a field, and return either "yes" or "not" which query would be the most effestive?
9
13706
by: Simon Withers | last post by:
I have 3 data tables, A, B and C, with many to many relationship tables between A-B and A-C. The data in A and C changes rarely, and the A-C relationship relates all possible combinations of A to a C If A contains A.1 to A.3 and C contains C.1 - C.8 then A-C could contain the records: A.1, C.1
4
2652
by: Orion | last post by:
Hi, This is kind of last minute, I have a day and a half left to figure this out. I'm working on a project using ms-sqlserver. We are creating a ticket sales system, as part of the system, I need to be able to do a search for specific tickets withing price ranges, different locations within the theaters, etc. etc. My problem is in the search one of the criteria is to search for a group of seats together. For example let's say...
3
7795
by: krystoffff | last post by:
Hi I would like to paginate the results of a query on several pages. So I use a query with a limit X offset Y to display X results on a page, ok. But for the first page, I need to run the same query with a count(*) to know how many pages I will get (number total of rows/ X). The problem is my query is very slow (maybe 5s) because there is much
2
8524
by: Mike Leahy | last post by:
Hello all, This question is related to updating tables - is there any way to calculate or update the values in a column in a table to the values in a field produced by a query result? An example of what I'm trying to do is below: update (tbl_ind_mananas LEFT JOIN (select count(*) as count, (dubicacion || zona || manzana) as cod_manzana from tbl_censo_poblacion_1993 group by dubicacion, zona, manzana) tbl1 on relacion = cod_manzana) as...
6
1906
by: Steven D.Arnold | last post by:
I have a query which does not use column indexes that it should use. I have discovered some interesting behaviors of Postgres which may indicate a bug in the database's query planning. Take a look at the query below. There is a btree index on both m.account_id and a.account_id. Query (1) does not use the index on the messages table, instead opting for a full table scan, thus killing performance. The messages table can contain...
1
311
by: Dimitris | last post by:
Hi all. I have an access 2000 database with one table with two fields. Both fields have telephone numbers(like telephone calls).I need to make a query to count how many times one number call another and if its possible wich numbers call the same telephone number.Thank you.
6
2558
by: geronimo_me | last post by:
I have 20 queries that compare fields in one table with fields in another table - the query results are the records that do not match in Table1 and Table2. ie Table1 DOB 28/02/78 Table2 DOB 27/02/78
8
3711
by: Maxi | last post by:
There is a lotto system which picks 21 numbers every day out of 80 numbers. I have a table (name:Lotto) with 22 fields (name:Date,P1,P2....P21) Here is the structure and sample data: "Date","P1","P2","P3","P4","P5","P6","P7","P8","P9","P10","P11","P12","P13","P14","P15","P16","P17","P18","P19","P20","P21" 1/1/2005,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21 1/2/2005,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22
1
3672
by: sunilkeswani | last post by:
Hi I am still new to access. I want to know how i can build a query which can display results from 4 different columns/fields Like. Field1 Field2 Field3 Field4 1 2 1 0 1 1 0 0
0
8352
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8802
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8465
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8579
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6158
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5612
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2699
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1909
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1587
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.