SQL Server : using another table as a 'lookup' - sql

I am selecting some data from a table where one of the columns is a value that defines a person. The value is unique to that person but can appear multiple times in the table.
I have no documentation whatsoever on the db - the details of the person (name etc) are held in another table, but that has a different ID column and does not reference the ID in the first table.
There is a third table (stay with me!) that contains both the ID from the first table, and the id from the second table. So I'm trying to use this to create a 'link' between the two IDs, so I can then grab the person data I need from the second table. The third table contains many more records than the other two.
I've tried various joins but the data I get back always contains duplicates, and incorrect IDs. I'll try and give an example:
Table 1 (the table I'm querying):
AgentID
Date
Time
9000
1/1/2022
12:00:00
9000
1/2/2022
15:00:00
9001
1/1/2022
13:00:00
9001
1/2/2022
17:00:00
Table 2 (the user info):
UserID
Name
1000
Fred Bloggs
1001
John Smith
Table 3 (the 'link'):
UserID
AgentID
Other Data
1000
9000
…
1001
9001
1001
9001
1000
9000
1001
9001
1000
9000
etc
Neither UserID or AgentID are PKs or FKs in the respective tables (don't ask - we didn't design this....)
Is there a way to do what I'm trying to do? It seems there should be but I've hit a brick wall.
Example of what I've tried:
SELECT
table2.name, table1.date,table1.time
FROM
table2
LEFT JOIN
table3 ON table3.agentID = table1.agentID
LEFT JOIN
table2 ON table2.UserID = table3.UserID
I've tried inner and right joins as well, same results.
Do I need to be doing some sort of 'nested' join?

you should use Subquery, first you should join table1 with distinct value of table3(Link), second you should join table2 (UserInfo)with table link. following query
SELECT U.Name,
T.Date,
T.Time
FROM table1 t
JOIN (SELECT DISTINCT UserID,
AgentID
FROM table3) L
ON T.AgentID= L.AgentID
JOIN table2 U
ON L.UserID= U.UserID
you should change the query per the names of your tables.

Related

In SQL, how to join multiple foreign keys IDs in multiple columns of a table to a single primary key in another table and uniquely select one?

Table A: Patient Encounters With Linked Diagnoses(DX)
Encounter_ID
Date
Primary_DX
DX_2
DX_3
DX_4
11111
01/01/2020
234234
256756
254537
678688
11112
05/01/2020
344564
234553
6786667
234234
11113
01/01/2022
123233
656444
678688
535465
11114
01/01/2021
435345
666654
3453453
456448
Table B: Diagnoses(DX) Code Linked with Their respective ICD Code
NOTE: The codes for this table is filtered for DX_ID/ICD_CODE's specifically for heart disease.
DX_ID
ICD_CODE
234234
N123.42
344564
N45.32
234553
N153.24
678688
N365.34
I seek to get only the encounters with the following condition:
At least one of the Primary_DX, DX_2,DX_3,DX_4 codes in Table A is a heart disease, that is, their respective diagnosis code can be linked to table B.
From this list, I seek to only get the ICD_Code for only that heart disease diagnosis code.
I have to do this in two steps:
Get all encounters where at least one of the DX_code in Table A is a DX_Code in Table B.
From this temporary table, select only the heart disease code and retrieve the ICD_code. If there are multiple heart disease for a single encounter, then they will show up as two separate rows.
So final output could have the following format:
Encounter_ID
ICD_CODE
11111
N123.42
11111
N45.32
11112
N123.42
11115
N15.42
11114
N123.42
Now filter for heart disease dx_codes with the EXISTS cause as below:
SELECT
Enounter_ID,
Primary_DX,
DX_2,
DX_3,
DX_4,
FROM
TABLE_A
WHERE
EXISTS (SELECT 1 FROM TABLE_B)
But I am getting encounters where NONE of the linked diagnoses are from the heart disease table.
Wouldn't this be enough ?
select Encounter_ID, ICD_CODE
from Table_A, Table_B
where Primary_DX = DX_ID
or DX_2 = DX_ID
or DX_3 = DX_ID
or DX_4 = DX_ID
order by Encounter_ID

TSQL Two different tables, 800GB vs 2GB Find common

I have two tables, generatedblock table, and addresses table
The generatedblock table has a column called expandedblock block.
The addresses table has a column called address.
What I need to do is find if in the generatedblock table there is a value in the addresses table.
I have tried failed code but I am not reposting because my tsql sucks,
How do I check every row in the address table, or visi versa contains a value, and to list the value in a temp table.
table generatedblock column expandedblock
-------------
1234
2334
4567
9878
4353
2345
3456
table addresses column address
-------------
1111
2222
3333
4444
5555
6666
1234
i get result return more than 1 row and I want those rows
SELECT *
FROM generatedblock
WHERE ExpandedBlock in (SELECT DISTINCT address FROM addresses)
You might be looking for INNER JOIN:
SELECT *
FROM generatedblock A
INNER JOIN address B
ON A.ExpandedBlock = B.address;

Update records from Linked table

How to update records in a Existing table.
I have two tables studentinfo , studentrecords
Table : Student info:
HTID Class BadgeID Location Begindate
133 T1 .## NJ 2018-01-31
I updated BadgeID to .### in studentinfo table.
Student records table contain
ID Badge Location Name Date
133 02311.01 NJ Steve 2018-01-31
How can i update the Student records table.
Result should be:
ID Badge Location Name Date
133 02311.001 NJ Steve 2018-01-31
You shouldn't. You should remove badgeId from one of the tables, and use a JOIN to fetch it when you need it.
Repeating data in different tables is a really bad idea in a relational database. It just introduces opportunities for incompatibilities and confusion.
use join
update s
set s.badge=r.badge
from
Studentinfo s join StudentR r on s.HTID =r.id
but it seems you need select query from output
select s.TID,r.Badge,s.Location,r.Name,
,r.Date from Studentinfo s join StudentR r on s.HTID =r.id

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

SQL2005 + return distinct result based on datetime on table in inner join

Im having a moment, what i want to do is really simple and i think im just looking at the wrong solution. I want to simply return a table that is sorted based on a datestamp of a related table.
ie:
Table 1:
200 MyStuff OK
201 Other Why
202 Flat So
Table 2:
1 200 5/12/2009 MyValue1
2 200 5/11/2009 MyValue2
3 201 7/10/2009 MyValue3
4 201 7/08/2009 MyValue4
I want the to return the first table sorted based on the dates in the second table, so my result should be
201 Other Why
200 MyStuff OK
202 Flat So
I have tried doing an inner join, but what i select distinct i have to include the date from the second table that im sorting on, thus i end up with duplicate pk's on the return table.
Please help me understand my rookie mistake here.
Since you can have multiple rows in Table2 for every row in Table1, you'll have to decide on how to handle the dates as far as sorting.
Let's say you want to sort on the maximum date stamp, you'd do something like:
select table1.*, t2.max_ds
from table1
inner join (select id, max(datestamp) as max_ds from table2 group by id) t2
on t2.id = table1.id
order by t2.max_ds
You'll obviously have to add some null handling and whatnot, but that should get you started.