SQL Server - Can someone explain this Query? - sql-server

I have a query that I can't understand. Can someone explain to me what is going on with all these commas ?
SELECT * FROM TABLE1
LEFT OUTER JOIN TABLE2 ON TABLE1.Column1 = TABLE2.Column1,
TABLE3, TABLE4, TABLE5, TABLE6
WHERE [...]
I don't get the part where a bunch or tables are listed. I figured out by the WHERE part that it was bound or at least used like in a "FROM" use. Can someone explain to me what is it and the name or at least have a link to the documentation of this form of link ?
Thanks a lot.

This means you Are Joining TABLE1 and TABLE2 using LEFT JOIN
So If there is a Matching value in TABLE2.Column1 for TABLE1.Column1 that Value will be displayed and if there is no Match, then the Column Will be there but Value will be NULL
For all other Tables, you are using a CROSS JOIN. So It will create a Cartesian Product with the Records obtained from the First Join
DECLARE #TABLEA TABLE
(
ColA INT
)
DECLARE #TABLEB TABLE
(
ColB INT
)
DECLARE #TABLEC TABLE
(
ColC INT
)
DECLARE #TABLED TABLE
(
ColD INT
)
INSERT INTO #TABLEA
VALUES(1),(2),(3)
INSERT INTO #TABLEB
VALUES(4),(5),(6)
INSERT INTO #TABLEC
VALUES(7),(8),(9)
INSERT INTO #TABLED
VALUES(10)
SELECT
*
FROM #TABLEA A
LEFT JOIN #TABLEB B
ON A.ColA = B.ColB
,#TABLEC,#TABLED
In the above Example, TableA and TableB are LEFT JOINed and then TABLEC AND TABLED are Cross Joined with the Result. So my Final Output will be
ColA ColB ColC ColD
----------- ----------- ----------- -----------
1 NULL 7 10
1 NULL 8 10
1 NULL 9 10
2 NULL 7 10
2 NULL 8 10
2 NULL 9 10
3 NULL 7 10
3 NULL 8 10
3 NULL 9 10
You Can Filter the Records from any of the tables using the WHERE Clause

Related

How to join the table

Here i have 2 tables and i need to join the table as i am a beginner please help me to solve
Table1 Table2
ins1 ins2 ins3 Insc0
1 2 0 1
3 4 0 2
5 6 0 3
4
5
is this below code right?
select t2.insco from table1 t1
join table2 t2 on t1.ins1=t2.insco
union
select t2.insco from table1 t1
join table2 t2 on t1.ins2=t2.insco
union
select t2.insco from table1 t1
join table2 t2 on t1.ins3=t2.insco
As I mentioned, you need to normalise your data. This is every much overly simplified, due to the simplicity of your data, however, should get you on the right path:
CREATE TABLE dbo.YourTable1 (RowID int--,
--Other columns, but no ins1, 2, etc columns
);
INSERT INTO dbo.YourTable1 (RowID--,
--Other columns
)
VALUES(1),(2),(3);--Obviouslu, again you would have other columns, but not an ins columns
CREATE TABLE dbo.YourTable2 (Insc0 int);
INSERT INTO dbo.YourTable2 (Insc0)
VALUES(1),(2),(3),(4),(5);
CREATE TABLE dbo.LinkTable (RowID int,
Ins int);
INSERT INTO dbo.LinkTable (RowID,
Ins)
VALUES(1,1),(1,2),
(2,3),(2,4),
(3,5),(3,6);
GO
SELECT *
FROM dbo.YourTable1 YT1
JOIN dbo.LinkTable LT ON YT1.RowID = LT.RowID
JOIN dbo.YourTable2 YT2 ON LT.Ins = YT2.Insc0;
GO
--Clean up
DROP TABLE dbo.LinkTable;
DROP TABLE dbo.YourTable2;
DROP TABLE dbo.YourTable1;

Joining tables without a common column in sql server

TABLE1
ID
----
1
2
3
4
5
TABLE2
Name
----
Z
Y
X
W
V
Expected Output:
ID Name
-------------------------
1 NULL
2 NULL
3 NULL
4 NULL
5 NULL
NULL Z
NULL Y
NULL X
NULL W
NULL V
I need a solution for the above scenario by using JOINS in SQL Server.
Using FULL OUTER JOIN, you can get the expected result.
Since there are no common fields, no records from Table1 should match with Table2 and vice versa. So perhaps ON 0 = 1 as the join condition also will work as expected. Thanks Bart Hofland
So the query below also will work:
SELECT T1.Id, T2.[Name]
FROM Table1 T1
FULL OUTER JOIN Table2 T2 ON 0 = 1;
or
SELECT T1.Id, T2.[Name]
FROM Table1 T1
FULL OUTER JOIN Table2 T2 ON T2.[Name] = CAST(T1.Id AS VARCHAR(2));
Demo with the sample data:
DECLARE #Table1 TABLE (Id INT);
INSERT INTO #Table1 (Id) VALUES
(1),
(2),
(3),
(4),
(5);
DECLARE #Table2 TABLE ([Name] VARCHAR(1));
INSERT INTO #Table2 ([Name]) VALUES
('Z'),
('Y'),
('X'),
('W'),
('V');
SELECT T1.Id, T2.[Name]
FROM #Table1 T1
FULL OUTER JOIN #Table2 T2 ON 0 = 1;
Output:
Id Name
-----------------
1 NULL
2 NULL
3 NULL
4 NULL
5 NULL
NULL Z
NULL Y
NULL X
NULL W
NULL V
I don't understand why you'd want this, but to get your expected results you could do this. This is not a join, though.
SELECT ID, NULL as NAME from Table1
UNION ALL
SELECT NULL, NAME from Table2
Edited to add
Since the question specifically requests a solution with a join, Arulkumar's answer of FULL OUTER JOIN is a better fit, and you don't have to worry about what the column data types are.

SQL joined table pivot without aggregate

I have two tables:
Table1
ID TYPE
1 ABC1
2 ABC2
3 ABC3
Table2
ID Data
1 100
1 101
2 10
2 90
And I want the results to look like this:
ID Data1 Data2
1 100 101
2 10 90
But I'm having a total mare with my attempts at creating the pivot. So far I have:
With Inital_Data As (
Select
A.ID,
B.Data As Data1,
B.Data As Data2
From
Table1 A join
Table2 B on
A.ID = B.ID
)
Select *
From
Initial_Data
PIVOT
(Max(ID) FOR Data IN (Data1,Data2)) p
I know this is rubbish but so far even the logic of what I'm trying to achieve is escaping me, let alone the syntax! Can anyone give me a guiding hand?
Pivot with more than one column needs some tricks, I prefer the XML concatenation. First I take all values for each ID in only one XML, then you can take these values one by one:
Just paste this into an empty query window and execute. Adapt for your needs
EDIT: Includes column Type from TABLE1 as Caption for ID...
DECLARE #Table1 TABLE(ID INT,[TYPE] VARCHAR(10));
INSERT INTO #Table1 VALUES
(1,'ABC1')
,(2,'ABC2')
,(3,'ABC3');
DECLARE #Table2 TABLE(ID INT,DATA INT);
INSERT INTO #Table2 VALUES
(1,100)
,(1,101)
,(2,10)
,(2,90);
WITH DistinctIDs AS
(
SELECT DISTINCT tbl2.ID,tbl1.[TYPE]
FROM #Table2 AS tbl2
INNER JOIN #Table1 AS tbl1 ON tbl1.ID=tbl2.ID
)
SELECT ID,[TYPE]
,concatXML.x.value('/root[1]/item[1]/#data','int') AS Data1
,concatXML.x.value('/root[1]/item[2]/#data','int') AS Data2
FROM DistinctIDs AS dIDs
CROSS APPLY
(
SELECT ID AS [#id],DATA AS [#data]
FROM #Table2 AS tbl WHERE tbl.ID=dIDs.ID
FOR XML PATH('item'), ROOT('root'),TYPE
) AS concatXML(x)

Update table gives primary key violation error

I have following tow tables
create table #temp(id int,rid int)
insert into #temp
select 1,1
union all
select 2,1
union all
select 3,1
select * from #temp
drop table #temp1
create table #temp1(id int, nid int,PRIMARY KEY CLUSTERED
(
id asc,nid asc
))
insert into #temp1
select 1,10
union all
select 2,10
union all
select 2,11
union all
select 3,10
Following are the both result sets:
id rid
1 1
2 1
3 1
id nid
1 10
2 10
2 11
3 10
I want to update #temp1 table with value from rid field of #temp table by matching id field from both tables. See following query:
select a.*
from #temp1 a inner join #temp b
on a.id = b.id
where a.id <> b.rid
It returns:
id nid
2 10
2 11
3 10
I want to update id with following query:
update a
set a.id = b.rid
-- select a.*
from #temp1 a inner join #temp b
on a.id = b.id
where a.id <> b.rid
But it returns
primary key violation error because of primary key in table #temp1.
I would like to delete the value if it is already exist if not then I would like to update
for example
id nid
1 10
2 10-- want to update but not able to this bcoz it violates primary key so delete this row.
2 11-- able to update this row but other 2 rows causing an issue.
3 10-- want to update but not able to this bcoz it violates primary key so delete this row.
Please suggest other ways to do this.
Because You are Violating the Primary Key Constraints
Check Below Tables
select B.*
from #temp1 a inner join #temp b
on a.id = b.id
where a.id <> b.rid
id rid
2 1
2 1
3 1
select * from #temp1
id nid
1 10
2 10
2 11
3 10
You are setting ID of above first table using join from #temp which already in #temp1
You Are attempt to Update Values which are already in #temp1 where id=2,2,3
select *
from #temp1 a inner join #temp b
on a.id = b.id
where a.id <> b.rid
You would be updating two id 2 records to the same value. You cannot do this, period. There is no other method to fix this except to drop the PK which I would suggest would be bad idea.
It is possible you need some further definition in your pdate to specify which of multiple records you want to update or you may need to delete the record which might end up as a duplicate before you do the update. Not knowing the business rules for what you are actually trying to accomplish or what your data means, it is impossiblet say what you can do to solve your problem. This ia case where the solution is dependant on the meaning and of course we have no meaning here.

T-SQL: Left Join and returning a null when no join is made

I have the following table, TableA, with some data
ColA ColB
0 5
0 6
I have another table, TableB, with some data
ColC ColD ColE
5 10 5
5 15 10
6 20 10
ColC is the foreign key for ColB. For each row in TableA I need to return ColA, ColB and ColD. The row to select in TableB depends on the value of ColE that is set through a parameter.
For example: If my parameter is set to 5, I should get two rows back as follows:
ColA ColB ColD
0 5 10
0 6 null
However, if my parameter is anything other than 5 and no row exists in TableB, it uses a parameter value of 5 instead and retrieves the value from ColB (if a row exists).
I tried several things but can't seem to come up with the solution. Thank you for your help!
Try this:
select ColA, ColB, ColD
from TableA a
left outer join TableB b on (a.ColB = b.ColC and b.ColE = 5)
select a.ColA, a.ColB, COALESCE(b.ColD, b5.ColD)
from TableA a
left outer join TableB b
on a.ColB = b.ColC
and b.ColE = 6
left outer join TableB b5
on a.ColB = b5.ColC
and b5.ColE = 5

Resources