MS Access Query / Design - sql

I have a table with instances of employee events. Each row has an ID, employee name and an eventNumber among other data. I would like to find and count all instances of where “employee name” occurs in this table, thus counting all the events associated with that employee.
If there are 15 unique employees , I suppose I could write 15 separate queries to get this done. But, is there a more efficient way to do this?
Also, I would like to display the total number of events for each employee that gets returned from these queries in another table or visual display of some sorts. This is where I really don’t know what to do as I haven’t used access much but am much more familiar with SQL.
Thanks for everyone who could take some time to chime in with some advice. I appreciate it a lot

This is fairly straight-forward in SQL. You can GROUP BY the employee name to get an overall count. Adding GROUP BY to a SQL statement will allow you to perform aggregate functions on one or more columns. Aggregate functions include COUNT, SUM, MIN, and MAX.
Documentation about GROUP BY can be found here:
https://support.office.com/en-us/article/group-by-clause-84eeb766-25d2-4aa1-8eea-002bb65ef3a0
A couple examples:
This query groups by EmployeeName to get the total count of all rows in table by employee name.
SELECT
EmployeeName
, COUNT(*) AS NumberOfEvents
FROM table
GROUP BY EmployeeName
Additionally, if you would like to get counts by eventid and employee name, you can group by both employee name and eventid. The query will then show the count of each type of event for each employee name.
SELECT
EmployeeName
, EventId
, COUNT(*) AS NumberOfEvents
FROM table
GROUP BY
EmployeeName
, EventId
If you would like to filter the results so that only one employee, 'Leroy Jenkins' is shown then you can add a WHERE clause as well, like this:
SELECT
EmployeeName
, COUNT(*) AS NumberOfEvents
FROM table
WHERE EmployeeName = "Leroy Jenkins"
GROUP BY EmployeeName
Responding to #WesG's comment asking for clarification.
The aggregate functions, like COUNT, are "rolling up" several rows in a table and displaying a single value for those rows. If your SELECT statement does not contain a GROUP BY clause, then the aggregate functions are working on all rows in the table.
When you do have a GROUP BY clause, then the aggregate functions will work on each group of rows that all have the same values in the columns by which you are grouping. Also, if you include a GROUP BY clause, then you may not SELECT columns that you are not GROUPing BY.
So, if you have a table like this:
CREATE TABLE [dbo].[AuditTrailLogs](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[EventType] nvarchar(20) NOT NULL,
[EventId] [int] NOT NULL,
[Message] [nvarchar](max) NULL,
[WhoDidIt] [nvarchar](50) NULL,
[WhenOccurredUtc] [datetime] NOT NULL,
[EntityPayload] [nvarchar](max) NULL,
)
You could count the total number of rows in the table like this:
SELECT COUNT(*) AS NumLogEntries
FROM dbo.AuditTrailLogs
If you wanted to count rows by the user who made the entry:
SELECT WhoDidIt, COUNT(*) AS NumLogEntries
FROM dbo.AuditTrailLogs
GROUP BY WhoDidIt
Then Access is going to split the rows in the table into a number of groups and COUNT will return the number log entries for each distinct value of WhoDidIt in the table.
If you want to see the totals by user who made the log entry and event type, then you could group by both columns:
SELECT WhoDidIt, EventType, COUNT(*) AS NumLogEntries
FROM dbo.AuditTrailLogs
GROUP BY WhoDidIt, EventType
Now, the NumLogEntries in each row of the result set will be the total of each event type that each user made.
Access will complain if you try to do something like this, though:
SELECT Id, WhoDidIt, EventType, COUNT(*) AS NumLogEntries
FROM dbo.AuditTrailLogs
GROUP BY WhoDidIt, EventType
If you think about it, this query doesn't make sense. The COUNT aggregate functions says you want to roll up multiple rows and display a single value for all those rows, however, you're also asking to see a value that isn't part of a group and is different for each row in the table.

something like
select employeeName, count(*) as nbEvents
from myTable
group by employeeName

Related

MS Access Count unique values of one table appearing in second table which is related to a third table

I am working with my lab database and close to complete it. But i am stuck in a query and a few similar queries which all give back the similar results.
Here is the Query in design mode
and this is what it gives out
This query is counting the number of ID values in table PatientTestIDs whereas I want to count the number of unique PatientID values grouped by each department
I have even tried Unique Values and Unique Records properties but all the times it gives the same result.
What you want requires two queries.
Query1:
SELECT DISTINCT PatientID, DepartmentID FROM PatientTestIDs;
Query2:
SELECT Count(*) AS PatientsPerDept, DepartmentID FROM Query1 GROUP BY DepartmentID;
Nested all in one:
SELECT Count(*) AS PatientsPerDept, DepartmentID FROM (SELECT DISTINCT PatientID, DepartmentID FROM PatientTestIDs) AS Query1 GROUP BY DepartmentID;
You can include the Departments table in query 2 (or the nested version) to pull in descriptive fields but will have to include those additional fields in the GROUP BY.

SQL*Plus Query help to sum and count from different table and get the correct answer

This is my query and is giving me the wrong amount. How can I fix it? It should be giving a total of 167700 but it is giving me 2515500 for the total loan. The count is working fine = 15. I can't change anything on the tables.
create table loan
(loan_number varchar(15) not null,
branch_name varchar(15) not null,
amount number not null,
primary key(loan_number));
create table customer
(customer_name varchar(15) not null,
customer_street varchar(12) not null,
customer_city varchar(15) not null,
primary key(customer_name));
select SUM(amount),
COUNT( distinct customer_name)
from loan,customer;
Simple rule: Never use commas in the FROM clause. Always use explicit, proper JOIN syntax with the conditions in the ON clause. Then you won't forget them!
So:
select SUM(amount),
COUNT( distinct customer_name)
from loan l join
customer c
on l.customerid = c.customerid;
Of course, I made up the names of the columns used for the join, because your question has no information describing the tables.
Duh! No common key in the two tables. How is that? How do you keep track of which customer took which loan?
Why are you running ONE query for data from two UNRELATED tables? The CROSS JOIN you created (by having no condition whatsoever on the enumeration of the two tables) simply joins every row from the first table to every row from the second table.
It appears the customer table has 15 rows, and all 15 names are distinct. When you COUNT DISTINCT, you get the correct number, even though in the cross join each customer_name appears many times.
On the other hand, each loan amount is repeated 15 times. 167,700 x 15 = 2,515,500.
If you need to show both the total loan amount and the number of (distinct) customers in a single row, you want something like
select (select sum(amount) from loan) as total_amount,
(select count (distinct customer_name) from customer) as distinct_customers
from dual
;

sql server: How can I show show category name although there is no record exisits

Can anyone help me to find a way to show category name, age, and total number of 0 even if there is no record exists? Now when I run the below SQL, it returns nothing. Thanks.
SELECT
'ADMISSION: ' AS CATEGORY_NAME
,AGE
,COUNT(ID) AS COUNTS
FROM table
GROUP BY AGE
Leave out the GROUP BY:
SELECT 'ADMISSION: ' AS CATEGORY_NAME,
COUNT(ID) AS COUNTS
FROM admission;
An aggregation query with no GROUP BY always returns one row. If you have a GROUP BY, then such a query will return no rows for an empty table (or if all rows are filtered out).
Also COUNT() doesn't return NULL. It returns 0 in this case.

PSQL not counting all entries

I am writing a count query which counts attendances at events over a few years. However there is a column named status in which it has extra information about attendance. Apology is listed when the person did not attend and thus should be excluded. status has various entries including group's letters, attendance information, guest status, as well as NULL entries.
The problem is that not all of the attendances are counted in full. They are counted in full when the status NOT LIKE 'Apology' is removed.
How can I get it to count all of the entries? Rather than a limited selection of 364 out of 1583.
I am using psql v9.3.11 in pgAdmin III v1.18.1.
The following is the relevant code:
SELECT b.attendances,
COUNT(b.attendances)
FROM (
SELECT COUNT(a.event_id) as attendances
FROM (SELECT DISTINCT event_id AS event_id,
member_pers_id AS member_pers_id
FROM event_attendance
WHERE status NOT LIKE 'Apology') a
GROUP BY member_pers_id
ORDER BY attendances) b
GROUP BY attendances
ORDER BY attendances ASC
I suspect the NOT LIKE is filtering out additional values, such as NULL. If so, then test for this explicitly.
Also, it makes no sense to do so many aggregations. One is sufficient:
SELECT COUNT(a.event_id) as attendances
FROM (SELECT DISTINCT event_id, member_pers_id
FROM event_attendance
WHERE status NOT LIKE 'Apology' OR status IS NULL
) a
And I'm not sure if the SELECT DISTINCT is necessary

How to insert a count column into a sql query

I need the second column of the table retrieved from a query to have a count of the number of rows, so row one would have a 1, row 2 would have a 2 and so on. I am not very proficient with sql so I am sorry if this is a simple task.
A basic example of what I am doing would be is:
SELECT [Name], [I_NEED_ROW_COUNT_HERE],[Age],[Gender]
FROM [customer]
The row count must be the second column and will act as an ID for each row. It must be the second row as the text file it is generating will be sent to the state and they require a specific format.
Thanks for any help.
With your edit, I see that you want a row ID (normally called row number rather than "count") which is best gathered from a unique ID in the database (person_id or some other unique field). If that isn't possible, you can make one for this report with ROW_NUMBER() OVER (ORDER BY EMPLOYEE_ID DESC) AS ID, in your select statement.
select Name, ROW_NUMBER() OVER (ORDER BY Name DESC) AS ID,
Age, Gender
from customer
This function adds a field to the output called ID (see my tips at the bottom to describe aliases). Since this isn't in the database, it needs a method to determine how it will increment. After the over keyword it orders by Name in descending order.
Information on Counting follows (won't be unique by row):
If each customer has multiple entries but the selected fields are the same for that user and you are counting that user's records (summed in one result record for the user) then you would write:
select Name, count(*), Age, Gender
from customer
group by name, age, gender
This will count (see MSDN) all the user's records as grouped by the name, age and gender (if they match, it's a single record).
However, if you are counting all records so that your whole report has the grand total on every line, then you want:
select Name, (select count(*) from customer) as "count", Age, Gender
from customer
TIP: If you're using something like SSMS to write a query, dragging in columns will put brackets around the columns. This is only necessary if you have spaces in column names, but a DBA will tend to avoid that like the plague. Also, if you need a column header to be something specific, you can use the as keyword like in my first example.
W3Schools has a good tutorial on count()
The COUNT(column_name) function returns
the number of values (NULL values will not be counted) of the
specified column:
SELECT COUNT(column_name) FROM table_name;
The COUNT(*) function returns the number of records in a table:
SELECT COUNT(*) FROM table_name;
The COUNT(DISTINCT column_name) function returns the number of
distinct values of the specified column:
SELECT COUNT(DISTINCT column_name) FROM table_name;
COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but
not with Microsoft Access.
It's odd to repeat the same number in every row but it sounds like this is what you're asking for. And note that this might not work in your flavor of SQL. MS Access?
SELECT [Name], (select count(*) from [customer]), [Age], [Gender]
FROM [customer]