What is the best way to join multiple datasets on multiple columns in MS Access? - sql

I have multiple (8-10) different datasets, all of which have a primary key (Name), some common columns and then some individual columns each. For example, table 1 might consist of Name, Date, Age, Username, LoginTime; table 2 Name, Date, MothersName,LoginTime, Age; table3 Name, Username, School, University, Age and so on and so forth.
Ideally I would like this all merged into a single table with unique columns: Name, Date, Age, Username, LoginTime, MothersName, School, University.
I know Access doesn't allow the use of covalesce - how can I go about creating this master table? I know what order I would like SQL to look in i.e. if Age is not in table 3, only then look in table 2 (even if table 2 has a value), and only then look in table 1 for that given Name. However I cannot work out how best to do the join so I don't get table1.Age, table2.Age, and table3.Age across all of my common fields...

Related

SQL Query to return a table of specific matching values based on a criteria

I have 3 tables in PostgreSQL database:
person (id, first_name, last_name, age)
interest (id, title, person_id REFERENCES person)
location (id, city, state text NOT NULL, country, person_id REFERENCES person)
city can be null, but state and country cannot.
A person can have many interests but only one location. My challenge is to return a table of people who share the same interest and location.
All ID's are serialized and thus created automatically.
Let's say I have 4 people living in "TX", they each have two interests a piece, BUT only person 1 and 3 share a similar interest, lets say "Guns" (cause its Texas after all). I need to select all people from person table where the person's interest title (because the id is auto generated, two Guns interest would result in two different ID keys) equals that of another persons interest title AND the city or state is also equal.
I was looking at the answer to this question here Select Rows with matching columns from SQL Server and I feel like the logic is sort of similar to my question, the difference is he has two tables, to join together where I have three.
return a table of people who share the same interest and location.
I'll interpret this as "all rows from table person where another rows exists that shares at least one matching row in interest and a matching row in location. No particular order."
A simple solution with a window function in a subquery:
SELECT p.*
FROM (
SELECT person_id AS id, i.title, l.city, l.state, l.country
, count(*) OVER (PARTITION BY i.title, l.city, l.state, l.country) AS ct
FROM interest i
JOIN location l USING (person_id)
) x
JOIN person p USING (id)
WHERE x.ct > 1;
This treats NULL values as "equal". (You did not specify clearly.)
Depending on undisclosed cardinalities, there may be faster query styles. (Like reducing to duplicative interests and / or locations first.)
Asides 1:
It's almost always better to have a column birthday (or year_of_birth) than age, which starts to bit-rot immediately.
Asides 2:
A person can have [...] only one location.
You might at least add a UNIQUE constraint on location.person_id to enforce that. (If you cannot make it the PK or just append location columns to the person table.)

SQL Query Involving Data From Different Tables

I have two different tables with records I need to join together in a way I can't quite figure out how to make work. My data looks like this.
Table A
Columns: Employee_ID, Employee_Department, Employee_Team, Manager_ID, Is_a_Manager ... many other columns
Sample Values:
12345 Department1 Team1 67890 Yes/No
.
.
.
One employee per row, several thousand rows comprising the entire company
Table B
Employee_ID, Manager_ID ... other columns
The exact same data set as Table A
Currently I'm combining those two tables (and three others) with a simple join on Employee_ID, which I'm then using as a data source in Tableau to visualize the data.
What I'd like to do with a SQL script is as follows:
Check to see whether an employee in Table A is a manager or not based on the Is_a_Manager column
If they are, find an employee in Table B who is one of their direct reports by matching the employee ID in Table A to the Manager ID in Table B.
Lookup that direct report's department and team in Table A by matching the Employee_ID in Table B to Employee_ID in Table A and displaying the Employee_Department and Employee_Team columns.
Add the direct report's department and team to two new columns in the original manager's Table A row
I'd like the final output in Table A to be something like
Employee_ID, Employee_Department, Employee_Team, Manager_ID, Is_a_Manager? ... Direct_Report_Department, Direct_Report_Team
Also, an important point is that some managers will have employees who are on different teams, so values in the Direct_Report_Department and Direct_Report_Team are not distinct. I only actually need any one employee's Department and Team to display, it doesn't matter which employee's it is.
Finally, I am able to do step 1 fairly easily in Tableau, so if the SQL script could do steps 2-4 and simply return a null value if the employee was not a manager, that would work for me as well.
Any ideas on how to accomplish this would be greatly appreciated. Thank you!
This should work based on the requirement provided. You don’t have to do any of the steps in Tableau and can simply export the output from the SQL as your data source
Select Tb1.Employee_ID, Tb1.Employee_Department, Tb1.Employee_Team, Tb1.Manager_ID, Tb1.Is_a_Manager, Tb3. Direct_Report_Department, Tb3. Direct_Report_Team
from Table_A Tb1
join (Select Manager_id, max(Employee_id) as emp_id from Table_B group by Manager_id) Tb2
on Tb1.Employee_id = Tb2.Manager_id
left join (Select Employee_ID, Employee_Department as Direct_Report_Department, Employee_Team as Direct_Report_Team from Table_A group by Employee_ID, Employee_Department, Employee_Team) Tb3
on Tb2.emp_id = Tb3.Employee_ID
where Tb1.Is_a_Manager = 'Yes';

Finding Values From Result of SQL Query in Different Table

I have multiple tables each connected by PersonID.
PhoneNumber contains columns for phone number type (work, cell, home), phone numbers, a value for whether SMS messaging is enabled, and person IDs.
Person contains names and email addresses and its key is person ID
AttributeValue contains the values for a number of 'custom' attributes (each attribute has a unique 'AttributeId'). The key columns in this table are AttributeId, Value, and EntityId. EntityId matches Person Id
I'm trying to find the corresponding names and email addresses from the PersonTable for the Person ID that meets the following criteria.
FROM [rock].[dbo].[AttributeValue]
WHERE AttributeId='1770';
FROM [rock].[dbo].[PhoneNumber]
WHERE IsMessagingEnabled=0 AND NumberTypeValueId=12
First of all in SQL when you got multiple tables related by one ID you can use joins.
For example I got a table Customer(ID,Name,Firstname) , a table Address(ID, CustomerID, Name, PostalCode, City) and a table Phone(ID,CustomerID,PhoneHome,PhoneMobile)
You can use this kind of query to find addresses and phones corresponding to customers :
SELECT [Address.Name], [Phone.PhoneHome], [Phone.PhoneMobile] FROM Address, Phone
INNER JOIN Address ON [Customer.ID] = [Address.CustomerID]
INNER JOIN Phone ON [Customer.ID] = [Phone.CustomerID]
WHERE [Customer.ID] = "Value"
Hope it will help you, at least you can find good examples of joints on :
http://openclassrooms.com/courses/introduction-aux-jointures-sql (I believe you're french so this is a good french site to learn about it.)
Have a good day
Something like this?
SELECT * FROM Person WHERE PersonID IN (SELECT PersonID FROM ....)

How to fetch data from two table in one go

I have a requirement where I have to fetch data from database table.
Condition is,
There are two tables with identical columns like name, mobile, address, age.
Ex. table names like Student and Teacher.
now if I don't find anything in student table then I will retrieve data from Teacher table.
how to write this query ?
To get results from the two tables you would use UNION ALL. Here however you only want to access table Teacher when there are no matching rows in table Student. This is slightly more difficult. You can still use UNION ALL, but need an EXISTS clause on your teacher query.
select * from student
union all
select * from teacher where not exists (select * from student);

sql query with "with and in clause"

i have a table which store user name, hobby and city .hobby field contain different hobby joined using "," operator eg swimming, basket, cricket. I want to search user name who match at least one hobby according to my search criteria.
You should not have multiple attributes in one column. That's one of the number one rules of 3nf database design. Now you have to figure out ways to parse this data. This issue only gets worse and worse each and every day. Seperate the hobbies as multiple rows in your database.
I agree with #JonH that there shouldn't be more than one piece of information in a column. It stops the row being truly atomic.
But you are where you are, and you can use the LIKE clause to return rows that match a substring within a column.
Something like:
select hobbycolumn from hobbytable where hobbycolumn like '%swimming%'
for example
To do this properly you need to restructure your tables if possible. For what you are looking for a possible way would be to have 3 tables. I'm not sure who the city belongs to, so I put it with the user.
1 for user with the following cols:
id
name
city
A table for for hobbies:
id
name
And a user_hobbies join table that allows each user to have multiple hobbies, and each hobby to have multiple users:
id
user_id (foreign key)
hobby_id (foreign key)
Then searching for a user with a certain hobby is:
SELECT user.id, user.name FROM user
INNER JOIN 'user_hobbies' on user_hobbies.user_id=user.id
INNER JOIN 'hobbies' on hobbies.id = user_hobbies.hobby_id
WHERE hobbies.name LIKE "query";