How to join two tables based on ID and get information - sql

Hello I need some help regarding SQL Query.
Table A
ID Name Type
---------------------
1 abc BC
---------------------
2 def SD
---------------------
3 ghi BC
----------------------
Table B (BC_ID and SD_ID are Foreign keys of Table 'B' referencing the Primary key 'ID' of Table 'A')
ID BC_ID SD_ID
---------------------
1 1 2
---------------------
2 3 2
---------------------
I am using VB.Net datagrid view to print the Table B details. I need to print 2 more columns in datagridview which specifies the Name of the corresponding BC_ID and SD_ID.
How do I write a SQL query which can get the 'Name' of the Corresponding ID's from the database and print in datagridview...
Expected Output in datagridview:
ID BC_Name SD_Name
---------------------
1 abc def
---------------------
2 ghi def
---------------------
I dont want to have separate BC_Name and SD_Name columns in the table B..I just need to join the two tables and get the name in a single query..Is it possible? Thanks in advance for your help

You need to join TableA twice with different alias names.
Try this:
SELECT B.ID,ISNULL(A1.NAME,'') as BC_NAME,ISNULL(A2.NAME,'') as SD_NAME
FROM TableB B LEFT JOIN
TableA A1 ON A1.ID=B.BC_ID LEFT JOIN
TableA A2 ON A2.ID=B.SD_ID
Result:
ID BC_NAME SD_NAME
1 abc def
2 ghi def
See result in SQL Fiddle.

Related

SQL join with composite key

I'm struggling with a SQL join query, maybe you could help me.
I have to join two tables. In one table, the primary key is a composite key from two columns to uniquely define a row.
In the other table, I just have one of these two rows.
Table looks like this:
Table 1
Type (PK)
Code (PK)
Description
f.e.
Type
Code
Description
0
A
potential A
0
A+
potential A+
1
1
Premium
1
2
Mainstream
2
EFI
EFI
2
LK
Local Key
3
100
exclusive
3
105
inclusive
In the second table, I have the code as the foreign key, but multiple times:
Table 2
Number (PK)
Name
Address
Code 1 (FK)
Code 2 (FK)
Code 3 (FK)
I want a query, where it shows me, f.e the customer name, code 1, code 2 and code 3 and the corresponding description.
If I have a query like this:
SELECT a.Number, a.Name, a.Code1, b.description, a.Code2, b.description
FROM Table1 a
INNER JOIN Table2 b ON a.Code1 = b.Code
it always shows me the first description. So, if Code 1 = A -> Description: potential A, if Code 2 = 1 -> Description = potential A - even if the correct description is "Premium".
I hope it's clear what I'm trying to do.
Thanks for your help!
Table 1 sample data:
Number (PK)
Name
Address
Code1
Code2
Code 3
Code 4
1587452
BMW
Downstreet5
A
2
LK
105
1887525
Audi
Abbyroad 7
A+
1
EFI
100
Table 2 sample data see above
Expected output:
New Query / View with
Name
Code1
Description Code 1
Code2
Description Code 2
BMW
A
potential A
2
Mainstream
What I get:
SELECT a.Number, a.Name, a.Code1, b.description, a.Code2, b.description
FROM Table1 a
INNER JOIN Table2 b ON a.Code1 = b.Code
| BMW | A | potential A | 2 | potential A | LK | potential A | 105 | potential A |
Solution if someone else does have the same problem:
I solved it with a subquery, like:
SELECT a.Number, a.Name, a.Code1,Description =
(SELECT b.description
FROM Table2 b
WHERE a.Code1 = b.Code),
a.Code2, Description =
(SELECT b.description
FROM Table2 b
WHERE a.Code2 = b.Code),
FROM Table1 a
Thanks for your help!

Joing on SQL table with arrays

I have two SQL tables
TABLE A
id | user | embedding
-----------------------
1 Ram [.12,.56]
2 Shyam [.23,.24]
3 Ghanshyam [.23,.39]
4 Balram [.34,.39]
TABLE B
--------------------
id | users
--------------------
1 [Ram,Shyam]
2 [Ram,Ghanshyam]
3 [Ram, Balram]
And I want to have a query that will return essentially table B but with the users replaced by their embeddings.
Desired output
-----------------------------
id | users
-----------------------------
1 [[.12,.56],[.23.,.24]]
2 [[.12,.56],[.23,.39]]
3 [[.12,.56], [.34,.39]]
How can I do this?
how about using unnest and array_agg:
select b.id , array_agg(embedding)
from TableB b
cross join unnest(b.users) c(user)
join TableA a
on c.users = a.user
group by b.Id

Compare the same column values in a table and then the take their relationship value from other table

I have a table like below:
ID Role CompanyID
1 T 123
2 S 1234
3 B 12345
T's company id has relationship with S's and B's company ids.The value of their relationship is in another table like below:
Rel CompanyId1 CompanyId
Private 1234 123
Public 12345 123
Of course first I have to join the two tables and then I have to get the relationship of T(123) with S(1234) and B(12345) from the table 2 and on the basis of that I have to create another column which will be if the relationship of T with S and B is private then 1 and if public then 0
It should be like this
Id Role Companyid BoolCol
1 T 123 for T there is no need to fill this col can be null
2 S 1234 1 becoz rel b/w T and S is private
3 B 12345 0 becoz rel b/w T and B is public
The relationship is only of T with another companies not the other way around
Any help will be appreciated.......
Thanks
You can join the table using Left join on CompanyId in first table and CompanyId1 in second table and use case when statement to get the BoolCol column.
select a.*,case when b.rel = 'Private' then 1
when b.rel = 'Public' then 0
else NULL
end as BoolCol
from table1 a
left join
table2 b
on a.companyid = b.companyid1;
Let me know in case you of any queries.
you can try this code:
select id, role,a.companyid,rel,case when rel='Private' then 1 when rel='Public' then 0 else null end as boolcol
from first_table a left join relation_table b
on a.companid=b.companyid1

Is there any difference in specifying a predicate in the ON or WHERE clause for an OUTER join?

If I have 2 tables A and B like this:
A:
id name
1 XXX
B:
id name
1
If i say:
select * from A left join B on a.id = b.id and b. name is not null.
Should I get any rows back?
Basically is the above query different from this query which will return 0 rows:
select * from A left join B on a.id = b.id where b. name is not null.
The queries are different.
Consider this data:
A:
id name
1 XXX
2 YYY
3 ZZZ
B:
id name
1 xxx
3 null
The first query keeps the join from matching on records from B where the name is null, so it returns:
id name id name
1 XXX 1 xxx
2 YYY null null
3 ZZZ null null
Notice that the id from B is null in the third record, because the join didn't match.
The second query matches records from B even if the name is null, but then it filters out all records where the name from B ends up as null (either from being null to start with, or because there is no matching record), so it returns:
id name id name
1 XXX 1 xxx
Predicates in the ON clause are evaluated at join time, whereas predicates in the WHERE clause are post-join filters. With an INNER join this does not matter, but with an OUTER JOIN it does.
So in your example, the first query should return one row (the row from B will not match on the join, but because it is a LEFT OUTER the row from A will be matched to all NULLs from B), and the second query should return zero rows (as the WHERE clause will be applied after the join, and filter out the one resulting row).
http://www-01.ibm.com/support/knowledgecenter/SSGU8G_11.50.0/com.ibm.sqls.doc/ids_sqs_1033.htm?lang=en refers to post-join filters.
Output from postgres:
postgres=# select * from A left join B on a.id = b.id and b.name is
not null;
id | name | id | name
----+------+----+------ 1 | XXX | | (1 row)
postgres=# select * from A left join B on a.id = b.id where b.name is
not null;
id | name | id | name
----+------+----+------ (0 rows)
postgres=#
They are not the same.
Putting the compound condition on the join tells the database to evaluate BEFORE the cartesean is generated. So in the 1st query. All records from A will be returned and those records which match A in B on ID will be returned if the name is not null.
In your second query the cartesean is generated first and then the not null evaluation occurs.
Expanding on the data provided
A:
ID name
1 xxx
2 yyy
3 zzz
B:
ID name
1
2 Bob
1st example would return:
1 XXX NULL NULL
2 YYY 2 BOB
3 ZZZ NULL NULL
All are returned as you indicated you wanted ALL Records, and only those records from B where the name wasn't null. but since the Null value identification occurs PRIOR to the Cartesian, only record 1 would be eliminated from table B But since it's in the section A where you wanted ALL records it would be included in the results.
2nd query would return
2 YYY 2 BOB
1 and 3 get EXCLUDED because Name is null, and this evaluation occurs AFTER the cartesean is generated.

Compare 2 tables in sql

I have two tables, A1 and A2. I want to compare these two tables. I tried inner join but it doesn't give the required result.
These are the data in these tables,
Table A1
No. Address
1 abc
1 abc
1 def
1 def
Table A2
No. Address
1 def
1 abc
1 abc
1 def
These two tables can only be joined by using No. column. So if I use INNER JOIN it gives 16 rows. I don't want that, I want only 4 rows to be displayed. This should be the output:
No. Address eq
1 abc #
1 abc *
1 abc #
1 abc #
Last column is displayed if address in A1 is equal to A2
Search for records that exist in A1 table but not in A2 table:
SELECT * FROM A1 WHERE NOT EXISTS (SELECT * FROM A2 WHERE A2.Id = A1.Id)
try to use case
select case when tablea1.address=tablea2.address then '*'
else '#' end as eq from tablea1 inner join tablea2 on tablea1.=tablea2.
hope it helps you.