Query in SQL Server to combine tables - sql-server

I need a query in SQL Server to combine tables like these:
TBL1
ID TITLE1
-----------
1 t1
2 t2
3 t3
TBL2
ID TITLE2
------------
100 c1
200 c2
Now I need tbl3 as a result:
TBL3
col1 col2
-----------
t1 c1
t1 c2
t2 c1
t2 c2
t3 c1
t3 c2
How can I get tbl3 without any key between these 2 tables?

You are looking for a cross join:
SELECT
t1.TITLE1 AS col1,
t2.TITLE2 AS col2
FROM TBL1 t1
CROSS JOIN TBL2 t2
ORDER BY
t1.TITLE1,
t2.TITLE2;
Demo

You can try this
CREATE TABLE #Table1
([ID] int, [TITLE1] varchar(2))
INSERT INTO #Table1
VALUES
(1, 't1'),
(2, 't2'),
(3, 't3')
CREATE TABLE #Table2
([ID] int, [TITLE2] varchar(2))
INSERT INTO #Table2
VALUES
(100, 'c1'),
(200, 'c2')
SELECT Title1 as col1, Title2 as col2
FROM #Table1
CROSS JOIN #Table2 order by Title1
DROP TABLE #Table1
DROP TABLE #Table2
Here is the output shown below.
col1 col2
t1 c1
t1 c2
t2 c2
t2 c1
t3 c1
t3 c2

CROSS JOIN will work for your case.
That is result-set contains the number of rows in the first table, multiplied by the number of rows in second table when there is no WHERE clause.
/**********************************/
SELECT
a.TITLE1 AS col1,
b.TITLE2 AS col2
FROM
TBL1 a
CROSS JOIN
TBL2 b
/**********************************/

Related

Select values from Three tables value not in another table MSSQL

I am using SQL Database. I am having three tables like T1,T2,T3. I want to get a column values from a table by excluding the values exists in another table.
SELECT T3 THEN
SELECT T2 NOT in T3 THEN
SELECT T1 NOT in T3 and T2
CREATE TABLE T1(CID INT,NAME VARCHAR(100),EMAIL VARCHAR(50), MOIBLE VARCHAR(20))
CREATE TABLE T2(CID INT,NAME VARCHAR(100),EMAIL VARCHAR(50), MOIBLE VARCHAR(20))
CREATE TABLE T3(CID INT,NAME VARCHAR(100),EMAIL VARCHAR(50), MOIBLE VARCHAR(20))
Insert value
INSERT INTO T1 VALUES (1,'TEST1','a#gmail','123456')
INSERT INTO T1 VALUES (2,'TEST2','b#gmail','123456')
INSERT INTO T1 VALUES (3,'TEST3','c#gmail','123456')
INSERT INTO T1 VALUES (4,'TEST4','d#gmail','123456')
INSERT INTO T2 VALUES (1,'TEST1','updateda#gmail','123456')
INSERT INTO T2 VALUES (2,'TEST2','updatedb#gmail','77777')
INSERT INTO T3 VALUES (1,'TEST1','updateda#gmail','999999')
Expected output
SELECT T3 and
SELECT T2 record NOT in T3 and
SELECT T1 record NOT in T3 and T2
cid Name email moible
1 TEST1 updateda#gmail 999999 From T3
2 TEST2 updatedb#gmail 77777 From T2
3 TEST3 c#gmail 123456 From T1
4 TEST4 d#gmail 123456 From T1
I have written query for this
SELECT * FROM T2 where cid not in ( SELECT cid from T3)
UNION
SELECT * FROM T3
Here How to include T1 table?
You can add anther 1 union cid not in T2 and T3
SELECT * from T1 where cid not in(SELECT cid FROM T2 where cid not in ( SELECT
cid from T3)
UNION
SELECT cid FROM T3)
UNION
SELECT * FROM T2 where cid not in ( SELECT cid from T3)
UNION
SELECT * FROM T3

How to select from table one with all records from table 2

I am trying to display all records that table 1 contains, each record with all the records from table 2 :
Table 1
company adress
------------------
A AdressX
B AdressY
C AdressZ
Table 2
Product Price
----------------
P1 50
P2 60
Result :
company Product
----------------
A P1
A P2
B P1
B P2
C P1
C P2
That would be a cross join.
SELECT t1.company,
t2.product
FROM [table 1] t1
CROSS JOIN [table 2] t2
ORDER BY t1.company,
t2.product;
Using CROSS APPLY this exected output is possible:
SELECT T1.company, T2.Product
FROM Table1 T1
CROSS APPLY Table2 T2
ORDER BY T1.company, T2.Product
Demo on db<>fiddle
Demo with sample data:
DECLARE #Table1 TABLE (company VARCHAR (1), adress VARCHAR (10));
INSERT INTO #Table1 (company, adress) VALUES
('A', 'AdressX'),
('B', 'AdressY'),
('C', 'AdressZ');
DECLARE #Table2 TABLE (Product VARCHAR (2), Price INT);
INSERT INTO #Table2 (Product, Price) VALUES
('P1', 50),
('P2', 60);
SELECT T1.company, T2.Product
FROM #Table1 T1
CROSS APPLY #Table2 T2
ORDER BY T1.company, T2.Product
Output:
company Product
---------------
A P1
A P2
B P1
B P2
C P1
C P2
The following query will select all data from both tables (not linked or related).
SELECT *
FROM TABLE 1
OUTER APPLY
(
SELECT *
FROM Table 2
) AS Table 2
If there is a foreign key, you can use a LEFT JOIN (SELECT)

How to join 2 tables with inner and left outer join

I have two tables in MSSQL with the same structure T1 & T2. Both tables can INNER JOIN on Id but T2 may not contain the AccountId associated with the Id as in T1.
.
T1 Id AccountId Name T2 Id AccountId Name
111 5555 John 111 5555 John
122 5555 David 133 5555 Sharon
133 5555 Sharon
Below is the code I tried but the result is not working?.
.
INSERT INTO T3
SELECT T1.Id,T1.AccountId,T1.Name
FROM T1
INNER JOIN T2 T2.Id = T1.id
LEFT OUTER JOIN T1.AccountId = T2.AccountId
WHERE AccountId = 5555
The expected result would be to insert values that are not in T1 into T3
You need where clause:
INSERT INTO T3(Id, AccountId, Name)
SELECT T1.Id, T1.AccountId, T1.Name
FROM T1 LEFT JOIN
T2
ON T2.Id = T1.id
WHERE T2.AccountId IS NOT NULL;
Notes:
Only one LEFT JOIN is necessary. I don't know what the INNER JOIN is for.
Every JOIN should be followed by an ON clause.
You should list the columns when doing an INSERT.
You need the WHERE to find non-matches.
This query could also be written using NOT EXISTS.
This should be what you're after:
CREATE TABLE #T1 (id int, AccountId int, [Name] varchar(6));
CREATE TABLE #T2 (id int, AccountId int, [Name] varchar(6));
CREATE TABLE #T3 (id int, AccountId int, [Name] varchar(6));
INSERT INTO #T1
VALUES (111,5555,'John '),
(122,5555,'David '),
(133,5555,'Sharon');
INSERT INTO #T2
VALUES (111,5555,'John '),
(133,5555,'Sharon');
INSERT INTO #T3 (id, AccountId, [Name])
SELECT T1.id,
T1.AccountId,
T1.[Name]
FROM #T1 T1
LEFT JOIN #T2 T2 ON T1.ID = T2.id
WHERE T2.id IS NULL;
SELECT *
FROM #t3;
DROP TABLE #T1;
DROP TABLE #T2;
DROP TABLE #T3;

Is CTE the correct way to handle recursion with two tables?

I have a query setup below, and I'm having trouble with the recursion piece. I start with a contract(s), Abc and Xyz from Table1. I take Table1.Id, groupNo and look them up in Table2, to get the contracts(s) there, then look those contracts back up in Table1, repeating the process until it eventually returns null, and capturing the last iteration. Is CTE the way to handle this? If so, could someone help with the last iteration. I tried nesting, and haven't got it to work.
Table Structure
create table Table1 (id int, groupNo int, contract varchar(3))
insert into Table1 values(33,2,'Abc')
insert into Table1 values(34,8,'Xyz')
insert into Table1 values(88,11,'123')
insert into Table1 values(89,11,'456')
create table Table2 (id int, groupNo int, contract varchar(3))
insert into Table2 values(34,8,'123')
insert into Table2 values(34,8,'456')
insert into Table2 values(89,11,'789')
Query
with myCTE (id,groupNo,contract) as
(
select
t1.id
,t1.groupNo
,t2.contract
from Table1 t1
inner join Table2 t2 on t1.id = t2.id and t1.groupNo = t2.groupNo
union all
select
t1.id
,t1.groupNo
,c2.contract
from myCTE c2
inner join Table1 t1 on c2.contract = t1.contract
)
select top 10 id, groupNo, contract
from myCTE
SQL FIDDLE
This is one way of doing it.
Basically, I record the level of each recursion and only keep the highest level. See SQL Fiddle and query below:
declare #Table1 table(id int, groupNo int, contract varchar(3));
insert into #Table1 values(33,2,'Abc');
insert into #Table1 values(34,8,'Xyz');
insert into #Table1 values(88,11,'123');
insert into #Table1 values(89,11,'456');
declare #Table2 table(id int, groupNo int, contract varchar(3));
insert into #Table2 values(34,8,'123');
insert into #Table2 values(34,8,'456');
insert into #Table2 values(89,11,'789');
with myCTE (level, id, groupNo, contract, subcontract) as
(
select 0, t1.id,t1.groupNo, t1.contract
,t2.contract
from #Table1 t1
inner join #Table2 t2 on t1.id = t2.id and t1.groupNo = t2.groupNo
union all
select level+1, c2.id, c2.groupNo, c2.contract
,t2.contract
from myCTE c2
inner join #Table1 t1 on c2.subcontract = t1.contract
inner join #Table2 t2 on t1.id = t2.id and t1.groupNo = t2.groupNo
)
Select c.* From myCTE as c
Inner join (select id, groupNo, contract, level = max(level) From myCTE Group by id, groupNo, contract) as m
On m.level = c.level and m.id = c.id and m.groupNo = c.groupNo and m.contract = c.contract
OPTION (MAXRECURSION 0);
I also added table2 to the second select. You want it to behave like the first one and it needs to get the subcontract name from table2.

Select record from table1 where value from table2

I have 2 tables here:
table1
id name idfrom idto
1 test 2 3
2 test3 1 9
table2
id branch status
2 a from
1 b from
9 c to
3 d to
How do I select branch from table2 and table1 based on status in table2?
I want the result to look like this:
id name branchfrom branchto
1 test a d
2 test3 b c
I answer it doesn't mean I like it.
SELECT id, name, bfrom.branch branchfrom, bto.branch branchto
FROM table1 t1
INNER JOIN (SELECT id, branch
FROM table2
WHERE status = 'from') bfrom
ON t1.idfrom = bfrom.id
INNER JOIN (SELECT id, branch
FROM table2
WHERE status = 'to') bto
ON t1.idto = bto.id;
I use INNER JOIN as sample only. You must adjust with your requirement (which you didn't clearly specify).
Something like the following should do (assuming you're wanting to join on id in both tables):
select t1.id, t1.name, f.branch as branchfrom, t.branch as branchto
from table1 as t1
join table2 as f
on f.id = t1.id
and f.status = 'from'
join table2 as t
on t.id = t1.id
and t.status = 'to'
This should work for you:
select t1.id, t1.name, f.branch as branchfrom, f1.branch as branchto
from table1 as t1
join table2 as f
on t1.idfrom = f.id
join table2 as f1
on t1.idto = f1.id
Please see here for demo: SQL Fiddle Demo
I don't know if this is better or worse than what the other two people have suggested but
select
t1.name,
(select
t2.branch
from
table2 t2
where
t1.idfrom = t2.id
) as branchfrom,
(select
t2.branch
from
table2 t2
where
t1.idto = t2.id
) as branchto
from
table1 t1
Here is a fiddle
Use this Code:
CREATE TABLE #table1 (
id int,
name varchar(10),
idfrom int,
idto int
)
CREATE TABLE #table2 (
id int,
branch char,
statuss varchar(10)
)
INSERT INTO #table1
VALUES (1, 'test', 2, 3)
INSERT INTO #table1
VALUES (2, 'test3', 1, 9)
INSERT INTO #table2
VALUES (2, 'a', 'From')
INSERT INTO #table2
VALUES (1, 'b', 'From')
INSERT INTO #table2
VALUES (9, 'c', 'to')
INSERT INTO #table2
VALUES (3, 'd', 'to')
SELECT
a.id,
a.name,
(SELECT
b.branch
FROM #table2 b
WHERE a.idfrom = b.id
AND b.statuss = 'FROM')
AS BranchFrom,
(SELECT
b.branch
FROM #table2 b
WHERE a.idto = b.id
AND b.statuss = 'to')
AS BranchTo
FROM #table1 a

Resources