multiple Access queries using same criteria - sql

New to this...
I have a table QAQC_Studies that includes titles, dates, and subject matter
I have another table QAQC_Publications that includes citation information for multiple publications resulting from a single study in the first table.
Every 3 months I need to create a report to QC studies added by coworkers so I run the following query (with some additional attributes removed for brevity). The where clause is a list of study IDs they provide me (often 15-20 different studies).
SELECT QAQC_Studies.StudiesID,
QAQC_Studies.NSL,
QAQC_Studies.StudyTitle,
QAQC_Studies.Abstract,
QAQC_Studies.StudyStatus
FROM QAQC_Studies
WHERE [QAQC_Studies].[StudiesID]=26806 or 26845
I'd like to add to that report a list of the publications associated with each study.
How do I write the Where clause in the second query to reference those studies indicated in the first query?

You can use a subquery. Something like:
SELECT [QAQC_Publications].[QAQC_Field]
FROM [QAQC_Publications]
WHERE [QAQC_Publications].[StudiesID] --or whichever field the two tables
--share for publication/study connection
IN (SELECT QAQC_Studies.StudiesID
FROM QAQC_Studies
WHERE [QAQC_Studies].[StudiesID]=26806 or 26845)

Related

I'm having trouble resolving a Internship postgresql exercise. Using two different tables

I've applied myself for a internship which uses postgresql, I never had any contact with programming language before the university which started just a couple months ago. The employer sent me an email with some exercises that I have to do before Monday. I have three days to learn the language and resolve the exercises. I've been studying the whole day, about 14 hours (for real). I'm getting used to the postgresql but I'm struggling with one thing. Since I'm very new to programming and I don't have enough time to do that very specific search I have no other options but ask you guys for.
Here's the problem. I have the same columns 'id_cliente' on both tables. I need to show a table where it shows all persons names, ids and how many movies each one of them borrowed from the rental.
I tried two different codes and none of them works.
select en_cliente.id_cliente, nome, count(en_aluguel.id_cliente) as alugueis
from en_cliente, en_aluguel
where en_cliente.id_cliente=en_aluguel.id_cliente
group by en_cliente.id_cliente;
Which makes Maria goes missing (Because her ID doesn't shows at the first table. It's supposed to show a zero
Also:
select en_cliente.id_cliente, nome, count(en_aluguel.id_cliente) as alugueis
from en_cliente, en_aluguel
group by en_cliente.id_cliente;
Which makes every value of the last column (id as alugueis) to be a '7'
First Table:
Second Table:
Third Table:
Two things:
Any time you have two tables in the FROM line, you’re doing an INNER JOIN, which requires matching rows on both tables.
Any time you have criteria in the WHERE clause, only rows matching that will be returned, which again will limit you to records in both tables with the clause you have.
You need to LEFT JOIN, which allows you to go from records that exist, to records that may or may not exist.
Give this a try. It will start at your en_cliente table and will join to your records in the en_aluguel table even if there is not a match in en_aluguel.
select en_cliente.id_cliente, nome, count(en_aluguel.id_cliente) as alugueis
from en_cliente
left join en_aluguel on (en_cliente.id_cliente=en_aluguel.id_cliente)
group by en_cliente.id_cliente;
Note: if you change the word “left” in my example to “inner”, you’ll end up with exactly the same code (just a different syntax) as your first example.

SQL 2 JOINS USING SINGLE REFERENCE TABLE

I'm trying to achieve 2 joins. If I run the 1st join alone it pulls 4 lots of results, which is correct. However when I add the 2nd join which queries the same reference table using the results from the select statement it pulls in additional results. Please see attached. The squared section should not be being returned
So I removed the 2nd join to try and explain better. See pic2. I'm trying to get another column which looks up InvolvedInternalID against the initial reference table IRIS.Practice.idvClient.
Your database is simply doing as you tell it. When you add in the second join (confusingly aliased as tb1 in a 3 table query) the database is finding matching rows that obey the predicate/truth statement in the ON part of the join
If you don't want those rows in there then one of two things must be the case:
1) The truth you specified in the ON clause is faulty; for example saying SELECT * FROM person INNER JOIN shoes ON person.age = shoes.size is faulty - two people with age 13 and two shoes with size 13 will produce 4 results, and shoe size has nothing to do with age anyway
2) There were rows in the table joined in that didn't apply to the results you were looking for, but you forgot to filter them out by putting some WHERE (or additional restriction in the ON) clause. Example, a table holds all historical data as well as current, and the current record is the one with a NULL in the DeletedOn column. If you forget to say WHERE deletedon IS NULL then your data will multiply as all the past rows that don't apply to your query are brought in
Don't alias tables with tbX, tbY etc.. Make the names meaningful! Not only do aliases like tbX have no relation to the original table name (so you encounter tbX, and then have to go searching the rest of the query to find where it's declared so you can say "ah, it's the addresses table") but in this case you join idvclient in twice, but give them unhelpful aliases like tb1, tb3 when really you should have aliased them with something that describes the relationship between them and the rest of the query tables
For example, ParentClient and SubClient or OriginatingClient/HandlingClient would be better names, if these tables are in some relationship with each other.
Whatever the purpose of joining this table in twice is, alias it in relation to the purpose. It may make what you've done wriong easier to spot, for example "oh, of course.. i'm missing a WHERE parentclient.type = 'parent'" (or WHERE handlingclient.handlingdate is not null etc..)
The first step to wisdom is by calling things their proper names

SQL to Spotfire query filtering issue with multiple tables

I am trying to calculate hours flowing in and out of a cost center. When the cost center lends out an employee for an hour it's +1 and when they borrow an employee for an hour it's -1.
Right now I'm using a query that says
select
columns
from dbo.table
where EmployeeCostCenter <> ProjectCostCenter
So when ProjectCostCenter = ID_CostCenter it returns +HoursQuantity.
Then I update ID_CostCenter = EmployeeCostCenter then where ID_CostCenter = EmployeeCostCenter to take -HoursQuantity.
That works fine. The problem is when I import it to Spotfire I can't filter on the main table even after I added the table relations. Can anyone explain why?
I can upload the actual code if needed, but I use 4 queries and a couple of them are quite lengthy. The main table, a temp table to calculate incoming hours, and a temp table to calculate outgoing hours are the only ones involved in this problem I think.
(moved to answer to avoid lengthy discussion)
Essentially, data relations are used to populate filtering / marking between different data-sets. Just like in RDBMS, the relation is what Spotfire uses as the link between dataset. Essentially it's the same as the column or columns you join on. Thus, any column that you wish to filter in TableA and have the result set limited in TableB (or visa versa) must be a relation.
Column matches aren't related columns, but are associated for aggregations, category axis, etc within each visualization. So if TableA has "amount" and TableB has "amount debit" and you wanted to use both of these in an expression, say Sum([TableA].[amount],[TableB].[amount debit]), they would need to be matched in order to not produce erroneous results.
Lastly, once you set up your relations, you should check your filter panel to set up how you want the filtering to work. You can have the rows included, excluded, or ignored all together. Here is a link explaining that.

Retrieve data from two different table in a single report

I have two table Employee and Salary table, salary consists Salary of employee in a field named Salary_employee.
Second one is Extra Expense, Extra expense consists records related to extra expenses of a company like electricity bills,office maintenance in a field named extra_expense.
(Their is no relationship between these two table).
Finally, I just wanted to show all the expenses of company in a report, for this i need to group both the table. what to use here join or union ??.
If there is no relationship between the two tables, then this really cannot work since you dont know where the expense is supposed to tie into. You should redesign the database if possible as this sounds impossible based on your description.
UPDATE
OK, by the look of your screenshots, I am guessing that this database only stores one companies info? And not multiple?
IF that is correct, AND if all you want to do is squish the data together into one flowing report of expenses, then I would indeed suggest a UNION. A JOIN would not give you the flow you are looking for. A UNION will just smash the two outputs together into one...which I think is what you are asking for?
SELECT ext_amount AS amount, ext_date AS date_of_trans
FROM extra_expenses
UNION
SELECT sal_cash AS amount, sal_dateof_payment AS date_of_trans
FROM employee_salary
It sounds like you don't need to use group or join. Simply query both tables separately within a script and handle them both accordingly to their structure to produce a report.
Join and union are functions which you can use to extract different information on a common thing from separate tables. E.g. if you have a user whose private details are stored in one table, but their profile information is in another table. If you want to display both private details as well as profile info, you can join the two tables by the common user name in order to combine and gather all info on the user in one query.

Nested Inner Join with identically named columns?

I am trying to come up with a SQL query string to read information from three tables, where they have overlapping column names:
Table: Task
Id
TaskDescription
...
Table: TaskAttempt
Id
TaskId
User
...
Table: TaskSubmission
Id
TaskAttemptId
Data
...
A task contains a description. Users can attempt to complete the task and they submit their results. Each task attempt can have multiple submissions.
When reviewing, I want to pull in all task submissions and display the description, user, and data; I also need to pull in all the Id fields so that I can update the rows upon review completion.
What would a SQL statement look like to capture this?
To deal with column names that are the same in different tables, you have to prefix the columns with the table that you are requesting the data from. This is a VERY basic shell of what your query would look like. The JOIN statements need the corresponding columns, but you did not provide the schema on how they match up. However, this answers your basic question about columns with the same name.
SELECT Task.Id, Task.TaskDescription, TaskAttempt.Id, TaskAttempt.User,
TaskSubmission.Id, TaskSubmission.Data
FROM Task
JOIN TaskAttempt
ON Task.Id = TaskAttempt.TaskId
JOIN TaskSubmission
ON TaskAttempt.Id = TaskSubmission.TaskAttempId
Prefixes simply give the SQL engine enough extra data to know how to handle ambiguities, and they also can provide much more expressive code to future readers.
You can specify which table to pull from using table_name.field, so:
SELECT Task.Id, TaskAttempt.Id, TaskSubmission.Id
FROM Task, TaskAttempt, TaskSubmission
You get the point. It is a good idea to use the table name on all fields whenever you are dealing with multiple tables. Example:
SELECT Task.Id, Task.TaskDescripton, TaskAttempt.Id...
FROM ...
Even though TaskDescription does not exist in the other tables, I still use the table name for clarity.