Help me with employee of the month query please - ms-access

HowI can do a query using the design view to show me the employee with higher sales in pesos per branch if I have 3 tables like the following?
Branches
- Branch
- Id branch
Employees
- EmployeeID
- Employee Name
- Assigned_branch
Sales
- Ticket Id
- Employee Id
- Public price
How can I get the Name of the employe who has the max sum of public price in all sales one per branch in only one query. I cannot use SQL in this and I really not use access frecuently. Please Help me!

I supose that your [Assigned_branch] field is a Foreign Key to [id branch] in table [Branches].
In design editor, drop the three tables into. Create a relation between the created field [Assigned_branch] from table [Employees] and [id branch] field in table [Branches]. Create another relation between table [Sales] field [Employee ID] and table [Employees] field [Employee ID].
On grid beneath, drop the fields [Employee ID] and [Employee Name] from table [Employees]. From table [Branches], drop all fields. From table [Sales] drop only the field [Public price].
Turn the query mode to "Totals", clicking in the "E" (sum) button. Group by all the columns on grid. In the column [Public price] from table [Sales], select the "Sum" totalization option. Order the colum "descending".
Now you have the rank of the better sales of your enterprise. If you want to retrieve only the bigger saler, you should do it quickly creating another query wich uses this one. Add the fields and, on column Sum_of_Sales created, select the "Max" option in the grid. Believe me, its easier than doing all things in just one query (getting totals and retrieving the Max value).
I hope I've helped. Please respond me if you have any doubt.

Open a new query, select the option to enter/view SQL code for the query, then paste the following and study the diagram that's created:
SELECT TOP 1 employeeid, [employee name], branch, sum(price) as total_emp_sales
FROM
employees AS e
INNER JOIN branches AS b ON e.assigned_branch = b.[id branch]
INNER JOIN sales AS s on e.employeeid = s.[employee id]
GROUP BY [employeeid], [employee name], branch
ORDER BY total_emp_sales DESC
Also, for future reference, it's not practical for any of us to try and describe how to use the designer to build the exact query you want. My advice is to get an intro book on SQL, to at least get a working knowledge of the language. Then you'll have a much better idea of how to use the designer.

Related

Simple SQL 2 Tables data grouping

I need to complete the following task in SQL:
Show the employment status in individual offices of the company in the following layout: office code, country, number of employees.
Table employees:
Table offices:
My idea was:
SELECT officeCode, (SELECT country FROM offices), COUNT(*)
FROM employees
GROUP BY officeCode
But it seems it doesn't work... Can you help?
Your main data set would be the office. Join to the employee's table by the office code. Then from your main table, get the data you need and then do a count( employee number)
Remember to add all the fields that you are displaying to the group by.

How to do a lookup or index/match in Access?

I'm new to access and I'm struggling on how to use lookups since vlookup is not available in Access. I want to get the values that correspond to a certain ID/tagging.
I have 2 tables.
Table A contains values let's say Product Number, Product Type, Price, Remaining Stock #, Product Type+Product Number Tag. Let's say product number is not unique but combining it with its product type, it will be unique so I created that tag.
Table B contains Seller's Name, # of items Sold, Product Number, Product Type, Product Type+Product Number Tag.
Now using Table A and Table B, how can I create a query/table that will allow me to use that "Product Number + Product Type" Tag when I try to get the price of that certain item so that I can get the total revenue of each seller.
I hope you understand what I'm trying to say. What I just want to do is I want to use this "Type+Number" Tag as a reference point in getting data of that respective item when I try to create queries/tables. It's just like an INDEX/MATCH in Excel. But how to do it in Access?
Please tell me if it's unclear.
Thank you!
You need to join your two tables based on the relationship between the Product Number & Product Type fields in both tables.
The two fields in Table A should be marked as the composite Primary Key (select both fields and in the Design ribbon click the Primary Key icon).
In Table B they will be Foreign Keys - a seller could sell those products more than once, so duplicates are allowed here.
You don't need the Product Type+Product Number Tag field.
The SQL for your query would then be:
SELECT *
FROM [Table A] LEFT JOIN [Table B] ON [Table A].[Product Number] = [Table B].[Product Number] AND
[Table A].[Product Type] = [Table B].[Product Type]
This will return all records from Table A and only those records from Table B that match the Primary Key.
Finally.... don't think of an Access table as an Excel spreadsheet. Access is all about the relationship between pieces of data - for a start queries can be expressed in plain English a lot easier.
E.g return all records from table B where seller name is "Dave" and date is between 1st Jan and 31st Jan would be written as:
SELECT *
FROM [Table B]
WHERE [Seller Name]='Dave' AND
[Sale Date] Between #01/01/2018# AND #01/31/2018#
(SQL only deals in US date format).
You can use DlookUp Function.
It can be used on queries as a calculated field, or in code in VBA:
For example, to get the price of a PRoduct, you could use something like:
DlookUp("[Price]";"Table A";"[Product Type+Product Number Tag]='" & Value & "'")
From my point of view, the complex part of DlookUp is the third argument, the WHERE clausule. If you have any experience with SQL, you will have no problem. If you don't, don't worry, just read some info and if you get stuck, come here to SO
You can use DlookUp to get any value of any field, based on a criteria (criteria applied to a unique field, ofc).
And yes, you can use it to get values from tables or from queries. In the link I provided before, it explains how the arguments works.
The most complex part is the criteria part. You must write as if you were typing a WHERE clausule on SQL more info here
About the criteria, always remember this:
If your criteria is a numeric value, then just type [field_criteria]=my_numeric_criteria
If your criteria is a text value, you must use single quotes. For example, [field_criteria]='my_text_criteria'
SQL requires single quotes around text values.
Try it!

Filtering Queries, Adding a field to a query that isn't in the table

I need help with sorting and adding a field to a query that hasn't been made yet.
For the first bullet, I'm confused at the last part where it asks you to sort by one field, and then within that field, sort again. "Sort the records in ascending order by Region, and within Region, by Product Name." How would I sort it only for Region? or am I not understanding the question...
And for the second bullet, how would I create the field "Extended Price" in a query when it hasn't been created in the table? I'm sure I could handle the rest of that but all I need to know is if there is a way to create a field through query without it being created in the table its based on...
Thank you. (BTW this is a practice question. This practice assignment in no way, shape, or form will benefit my grade)
Use the query builder to construct SQL. The result should be something like:
SELECT ProductID, ProductName, Category, UnitsInStock, UnitPrice, SupplierID, SupplierName, Region, UnitsInStock * UnitPrice AS ExtendedPrice FROM Products INNER JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID ORDER BY Region, ProductName;
select p.product_name,p.category,p.supplier_id,s.supplier_name,s.region,s.unitprice
from products p join supplier s
on p.supplier_id=s.supplier_id
BTW this may work , if you modify accordingly

Pulling different records from multiple tables as one transaction history list

I am working on an employee management/reward system and need to be able to show a single "transaction history" page that shows in chronological order the different events that the employee has experienced in one list. (Sort of like how in facebook you can goto your history/action section and see a chronological list of all the stuff that you have done and affects you, even though they are unrelated to eachother and just have you as a common user)
I have different tables for the different events, each table has an employee_id key and an "occured" timestamp, some table examples:
bonuses
customers
raise
complaints
feedback
So whenever an event occurs (ie a new customer is assigned to the employee, or the employee gets a complaint or raise) a new row is added to the appropriate table with the employee ID it affects and a timestamp of when it occured.
I need a single query to pull all records (upto 50 for example) that include the employee and return a history view of that employee. The field names are different in each table (ie the bonus includes an amount with a note, the customer includes customer info etc).
I need the output to be a summary view using column names such as:
event_type = (new customer, bonus, feedback etc)
date
title (a brief worded title of the type of event, specified in sql based on the table its referencing)
description (verbiage about the action, such as if its event_type bonus display the bonus amount here, if its a complain show the first 50 characters of the complaint message or the ID of the user that filed the complaint from the complaints table. All done in SQL using if statements and building the value of this field output based on which table it comes from. Such as if its from the customers table IF current_table=customers description='A customer was assigned to you by'.customers.assigner_id).
Ideally,
Is there any way to do this?
Another option I have considered, is I could do 5-6 different queries pulling the records each from their own table, then use a mysql command to "mesh/interleave" the results from all the queries into one list by chronological order. That would be acceptable too
You could use a UNION query to merge all the information together and use the ORDER BY clause to order the actions chronologically. Each query must have the same number of fields. Your ORDER BY clause should be last.
The examples below assume you have a field called customer_name in the customers table and bonus_amount in the bonuses table.
It would look something like this:
SELECT 'New Customer' as event_type, date,
'New customer was assigned' as title,
CONCAT('New Customer: ', customer_name, ' was assigned') as description
FROM customers
WHERE employee_id = 1
UNION
SELECT 'Bonus' as event_type, date,
'Received a bonue' as title,
CONCAT('Received a bonus of $', FORMAT(bonus_amount, 2), '.') as description
FROM bonuses
WHERE employee_id = 1
UNION
...
ORDER BY date DESC;

Update Calculated [Field] Base on the status of a Separate Table

I need to change the value of a Calculated FIELD depending on the results from a separate table.
I made up a small Fake DB(attached) to highlight my problem..
When the Database is open I want to be able to show on the first screen if ALL training is up to date for each employee, by changing the value of the "Calculated Field".
I have 5 Employees.
Each Employees must do 5(or more) training's.
All Training's must NOT be expired.
If a single training is expired Change Calculated Field Value to "NO GOOD"
If ALL training is NOT expired Change Calculated Field Value to "ALL GOOD"
I have no Idea on how to approach this scenario. Do I need to create a separate "Temp Table" to store this value?
Database found HERE: http://1drv.ms/1tX7L9M
I can't link pictures or more than 2 links yet so please look at these:
http://1drv.ms/1tXhr45
Here is my query.
SELECT Training.ID, Training.EmployeeID, Employees.Name, Training.TrainingID, Training.TrainingDate, TrainingList.Frequency, DateAdd("m",[frequency],[TrainingDate]) AS DueDate
FROM Employees INNER JOIN (Training INNER JOIN TrainingList ON Training.TrainingID = TrainingList.TrainingID) ON Employees.EmployeeID = Training.EmployeeID;
I need to check that all training for each Employee is current. If it is then I need to show this by changing the value from my first form.. The record source of the first form is like this:
SELECT DISTINCTROW Employees.ID, Employees.Name, Employees.EmployeeID, "Help With This Field" AS TrainingStatus
FROM Employees;
The Purpose of this is to make my life easier and be able to see at a glance which employees need to do recurrent training and which are up to date.. I still can't visualized how this can be done.. I am a (Google is my teacher kind of access user :( )
You have a query which computes the DueDate for all training records. Use it as the data source for another query in which you restrict the results to only those records whose DueDate has not already passed.
SELECT tq.*
FROM [Training Query] AS tq
WHERE (((tq.DueDate)>=Date()));
If that query returns the correct records --- only those trainings which have not expired --- reuse its WHERE clause in a GROUP BY query where you count up the number of unexpired trainings per each employee.
SELECT tq.EmployeeID, Count(tq.TrainingID) AS CountOfTrainingID
FROM [Training Query] AS tq
WHERE (((tq.DueDate)>=Date()))
GROUP BY tq.EmployeeID;
If that query also produces sane results, you can use an IIf expression to return "ALL GOOD" when CountOfTrainingID >= 5 and "NO GOOD" when it's < 5.
SELECT
sub.EmployeeID,
sub.CountOfTrainingID,
IIf(
sub.CountOfTrainingID >= 5,
'ALL GOOD',
'NO GOOD'
) AS TrainingStatus
FROM
(
SELECT tq.EmployeeID, Count(tq.TrainingID) AS CountOfTrainingID
FROM [Training Query] AS tq
WHERE (((tq.DueDate)>=Date()))
GROUP BY tq.EmployeeID
) AS sub;
That should get you most of the way to your goal. You would still need to join in the Employees table to get their names.
There may be other issues which you still need to address:
If an employee has not yet completed any trainings, or all his trainings have expired, should his name appear in the query (and form based on that query)?
Is your criteria based on 5 or more different trainings? For example, if an employee completed only the same training 5 times in the past month, should his TrainingStatus be good or no good?