MS Access VBA: Combine 2 SQL statements with a LEFT JOIN - sql

Hi all and thanks in advance for your help!
I am trying to use a JOIN to combine a fitlered SQL statement with a table in order to populate a combobox (makes sense?)
Here is the main SQL query:
MainSQLquery = "SELECT QuotationID, QuoteDate, EmployeeID FROM TestTable1"
I want to write a statement to use this with another table like so:
SELECT EmployeeID, EmployeeName
FROM MainSQLquery LEFT JOIN EmployeeTable
GROUP BY EmployeeID
But I can't get it right. I get a "Syntax error in FROM clause" even with something as simple as:
ComboSQL = "SELECT EmployeeID FROM " & MainSQLQuery
Me.Combo2.RowSource = ComboSQL
Do you guys know any way to do this?
*******BACKGROUND**********
For those of you who wants to see the bigger picture, I have a subform showing a list of quotations and based on a dynamic SQL statement, it is filetered with a WHERE clause based on different inputs and it looks like this when displayed:
QuoteID Quote date Employee ID
1 10/13 1
2 10/13 2
3 10/13 2
4 09/18 1
5 08/10 2
6 07/16 3
7 06/27 3
On the main form, I have comboboxes that I use to filter this subform, which works perfectly. But I also need my comboboxes to be filtered the same way as the subform content and without having any duplicate (that's the only thing I can't do right now).
So far I use the same filtered SQL query for the subform and all the comboboxes, so instead of having a neat Employee combobox that looks like this (with the example above):
1
2
3
I get that instead (same as the subform):
1
2
2
1
2
3
3
My idea is to have a main SQL query for the subform, and another SQLquery based on the main one for the comboboxes, something like that:
SELECT EmployeeID, EmployeeName
FROM MainSQLquery LEFT JOIN EmployeeTable
GROUP BY EmployeeID
if I could get this working, the filter would still be built in the mainSQL and I could group the EmployeeID field without problem.
I guess it should be fairly simple, but I can't get it right, there is something I don't know about using an SAL as source of another.
(I wish I could post pictures or a database sample, but a paranoid guy got my previous post deleted because of that, so it will have to do with text only, sorry about that)

When you have a JOIN you should have an ON to let the database know how to relate the tables:
SELECT EmployeeID, EmployeeName
FROM (
SELECT QuotationID, QuoteDate, EmployeeID
FROM TestTable1
) AS MainSQLquery LEFT JOIN EmployeeTable
ON MainSQLquery.EmployeeID = EmployeeTable.ID
GROUP BY EmployeeID
The LEFT JOIN gets all records from the table on the left of the join -- MainSQLquery -- and only the records from the right table -- EmployeeTable -- that match. If no matches are found in the right table, a NULL value is returned.
Given this example:
TestTable1
QuotationID | QuoteDate | EmployeeID
--------------------------------------------
1 10/1/2014 1
2 10/8/2014 2
3 10/5/2014 3
4 10/10/2014 1
5 10/20/2014 5
EmployeeTable
ID | EmployeeName
----------------------
1 Jeremy Smith
2 Pam Engles
3 Achim Flemmish
4 Sandra Hayes
This would be the result of the above query:
Result
EmployeeID | EmployeeName
--------------------------------
1 Jeremy Smith
2 Pam Engles
3 Achim Flemmish
5 NULL

Related

SQL query in postgresql to produce pivot table report to turn columns into rows

Unsure how to create a pivot report query in postgres (newbie to postgres) based on the following tables/report layout.
Please note that I am not able to change the structure of these tables as out of my control.
STOCK_REF ( sr_id, stock_name )
STOCK_INVENTORY ( si_id, sr_id, stock_count ) * where sr_id here is a foreign key constraint
Sample data for each table may include the following:
STOCK_REF
1 GUITAR
2 BASS
3 DRUMS
4 KEYBOARDS
STOCK_INVENTORY
1 1 10
2 2 5
3 3 2
4 4 15
Using the above two tables, I need to produce a report that looks like:
STOCK NAME COUNT
--------------------------- --------
GUITAR 10
BASS 5
DRUMS 2
KEYBOARDS 15
which is like a pivot table.
The thing is, I can write the query that will produce the stock name as columns with counts but I actually need to have the stock name and counts as rows, like above.
Any help with this postgres query would be ideal
Try the query below. It's simple SQL. I think POSTGRES don't determine too much here...
SELECT stock_name AS "STOCK NAME", stock_count AS "COUNT"
FROM STOCK_REF INNER JOIN STOCK_INVENTORY
ON (STOCK_REF.sr_id = STOCK_INVENTORY.sr_id)

Order by result of subquery in PostgreSQL

Assuming I have one table Employees with the columns id, name, salary and manager_id
and another table fields with the column field which can be any of the fields in the Employees table.
How can I sort the employees by the rows in the fields table?
For example: when fields contains the values 'salary', 'manager_id', the employees will be sorted by salary and then by manager_id.
I tried something like this but it didn't work:
SELECT * FROM employees ORDER BY (SELECT field FROM fields)
Edit: The original question was a simplified example of my goal.
I want that the employees will be sorted by their super manager id, then by the second super manager id...and in the end by their direct manager’s id.
Given the employees(id, name, salary, manager_id):
1 Alex 1000 NULL
2 Mor 2000 1
3 John 3000 NULL
4 Chris 4000 1
5 Michael 5000 4
6 Matt 6000 2
The query result will be:
1 Alex 1000 NULL
2 Mor 2000 1
6 Matt 6000 2
4 Chris 4000 1
5 Michael 5000 4
3 John 3000 NULL
You cannot do that in a single query.
First you have to query fields, then construct an SQL statement with the proper ORDER BY clause and run that.
Beware of SQL injection — use the format function to construct the query.
If you can tell us the error that it gives you it may help us helping you
what i think is that ' symbols are what making the issue so it will be as if you're writing:
SELECT * FROM employees ORDER BY 'salary', 'parent_id'
try replacing it with a blank character using Replace()
There is a way how this can be accomplished. But i strongly advice to change your design.
To support this you must add SEQ field in your Fields table to decide order of fields in Fields table. First field have SEQ 1, second 2 ...
SELECT
*
FROM
Employees E
ORDER BY
CASE
(SELECT
F.NAME
FROM
Fields F ORDER BY F.SEQ LIMIT 1)
WHEN 'salary' THEN E.salary
WHEN 'parent_id' THEN E.parent_id
ELSE 0 END
,
CASE
(SELECT
F.NAME
FROM
Fields F ORDER BY F.SEQ LIMIT 1 OFFSET 1)
WHEN 'salary' THEN E.salary
WHEN 'parent_id' THEN E.parent_id
ELSE 0 END
sample on sql fiddle to demonstrate. There are two tables FieldsA and FieldsB to make testing easier without need for delete from table Fields and new records to see if it is working.
http://sqlfiddle.com/#!15/64df6e/2/0

Excessive Case Statement Help - SQL Server

I'm supposed to answer this for class, and it's tricky (for me)
Write a SELECT query to output the name of all employees with the name of their supervisor. If the employee has no supervisor, the supervisor name column should contain the text 'No Supervisor'.
The primary key field in my db is the employeeid and they are provided with names, and each student also has a supervisorid
The table for this is shown below (sorry for the layout):
employeeid lastname firstname salary supervisorid
1 Stolz Ted 25000 NULL
2 Boswell Nancy 23000 1
3 Hargett Vincent 22000 1
4 Weekley Kevin 22000 3
5 Metts Geraldine 22000 2
6 McBride Jeffrey 21000 2
7 Xiong Jay 20000 3
I was wondering how I could go about this statement without using the case statement to apply each of the 7 students with:
when concat(firstname,' ',lastname)='Nancy Boswell' then 'Ted Stolz'
In larger tables this would simply be a HUGE statement, is there a better way to do it?
Thanks!
EDIT:
I've now tried this:
SELECT
EMP1.employeeid as 'employee',
EMP2.supervisorid as 'manager'
FROM
employee EMP1
LEFT OUTER JOIN
employee EMP2
ON
emp1.employeeid = emp2.supervisorid;
However, I am seeing duplicate fields, for some reason employee 2 and 3 are appearing twice, meaning there are 9 fields showing instead of 7.
Also, I need to display their names, not their id's does that mean I need to join the join that i've already done to the employee name ? How would I do this?
Thanks for the feedback guys!
You need to link the table with itself based on the supervisorId. This might be strange if you are new to SQL but it is very common to do. You tell with SQL to add the row of the supervisor to the row of the employee via its primary key.
SELECT
*
FROM
EMPLOYEES EMP1
LEFT OUTER JOIN
EMPLOYEES EMP2
ON
-- make link between tables here
Note that the above query is not 100% correct / complete, its an indication. The LEFT OUTER JOIN statement makes the employees without supervisor have null values for the supervisor, otherwise the whole record would be left out.

Simple SQL Select from 2 Tables (What is a Join?)

I'm new to SQL. I have a simple problem with getting the results from two different tables.
I have two tables in a database. The first table has a column with an id reference, which corresponds to rows in the second table. What SELECT do I need to perform to get a result such that the ids are repalced by all of the values in the second table. To visualize the tables I am discussing:
TABLE_USERS
===========
id username group
-- -------- -----
1 jim A
2 alice A
3 brandon B
TABLE_GROUPS
============
id groupname members
-- --------- -------
A designer 134
B photographer 39
DESIRED_SELECTION
=================
id username group
-- -------- -----
1 jim designer
2 alice designer
3 brandon photographer
Thanks!
You do, in fact, want to JOIN the two tables:
SELECT * FROM
TABLE_USERS LEFT JOIN TABLE_GROUPS
ON TABLE_USERS.group = TABLE_GROUPS.id
The trick of joining tables is to find the values that must match in the two tables, and use the on to tell SQL to match them. This table has a ID column to let you do that = you will join the table, ON, and then list the values that need to be equal.
If you do not want all of the columns in both tables, you can simply list only the columns you need in your final query. This means that instead of Select *, you list the columns you want. As shown below, if a column appears with the same name in both tables, you need to prepend the table name, so that SQL know which value you want.
SELECT TABLE_USERS.ID, Username, Groupname
FROM TABLE_USERS
LEFT JOIN TABLE_GROUPS
ON TABLE_USERS.group = TABLE_GROUPS.id
You want a JOIN:
SELECT
u.id,
username,
groupname
FROM
TABLE_USERS AS u
LEFT JOIN TABLE_GROUPS AS g
ON u.group = g.id

MySQL Query That Can Pull the Data I am Seeking?

On the project I am working on, I am stuck with the table structure from Hades. Two things to keep in mind:
I can't change the table structure right now. I'm stuck with it for the time being.
The queries are dynamically generated and not hard coded. So, while I am asking for a query that can pull this data, what I am really working toward is an algorithm that will generate the query I need.
Hopefully, I can explain the problem without making your eyes glaze over and your brain implode.
We have an instance table that looks (simplified) along these lines:
Instances
InstanceID active
1 Y
2 Y
3 Y
4 N
5 Y
6 Y
Then, there are multiple data tables along these lines:
Table1
InstanceID field1 reference_field2
1 John 5
2 Sally NULL
3 Fred 6
4 Joe NULL
Table2
InstanceID field3
5 1
6 1
Table3
InstanceID fieldID field4
5 1 Howard
5 2 James
6 2 Betty
Please note that reference_field2 in Table1 contains a reference to another instance.
Field3 in Table2 is a bit more complicated. It contains a fieldID for Table 3.
What I need is a query that will get me a list as follows:
InstanceID field1 field4
1 John Howard
2 Sally
3 Fred
The problem is, in the query I currently have, I do not get Fred because there is no entry in Table3 for fieldID 1 and InstanceID 6. So, the very best list I have been able to get thus far is
InstanceID field1 field4
1 John Howard
2 Sally
In essence, if there is an entry in Table1 for Field 2, and there is not an entry in Table 3 that has the instanceID contained in field2 and the field ID contained in field3, I don't get the data from field1.
I have looked at joins till I'm blue in the face, and I can't see a way to handle the case when table3 has no entry.
LEFT JOIN...
SELECT a.InstanceID, b.field1, d.field4
FROM instances AS a
JOIN Table1 AS b ON a.InstanceID = b.InstanceID
LEFT JOIN Table2 AS c ON b.reference_field2 = c.InstanceID
LEFT JOIN Table3 AS d ON (c.InstanceID = d.InstanceID AND c.field3 = d.fieldId)
WHERE a.active = 'Y'
The two left joins should handle the case where there are no other rows...
It would help if you posted the query you have, because I think you have some mistakes in the table descriptions here, so it's not very clear how are the tables connected.
Anyway, you probably have an inner join in your query (normally written as just JOIN). Replace it with a left outer join (LEFT JOIN). It will not require the right table to contain the row and return NULL instead of the actual value.