Join unrelated tables - sql-server

I want to join these two unrelated tables:
table 1
id name age
-- ---- ---
1 a 9
2 b 11
3 c 10
table 2
id school address
-- ------ -------
1 aa abc
1 aa efg
3 bb hij
Desired results:
id school address age name
-- ------ ------- --- ----
1 aa abc 9 a
1 aa efg 9 a
2 NULL NULL 11 b
3 bb hij 10 c

SELECT t1.id, t2.school, t2.address, t1.age, t1.name
FROM dbo.table1 AS t1
LEFT OUTER JOIN dbo.table2 AS t2
ON t1.id = t2.id
ORDER BY t1.id;

Related

Combine columns from tables into single table

I have four tables with data I want to put the respective total columns from each in a different column. However, I would like to match on dealerId. So if there is a dealerId in Table 1 and Table 3 that are the same, they should be a single row.
Table 1
dealerId | t1 Total Amount
---------+---------------
1 | 123
2 | 456
Table 2
dealerId | t2 Total Amount
---------+----------------
3 | 111
4 | 222
5 | 333
Table 3
dealerId | t3 Total Amount
---------+----------------
1 | 555
3 | 565
6 | 888
Table 4
dealerId | t4 Total Amount
---------+----------------
1 | 88
2 | 99
3 | 11
Desired Outcome
dealerId | t1Total Amount | t2Total Amount | t3 Total Amount | t4 Total Amount
---------+----------------+----------------+-----------------+-----------------
1 | 123 | null | 555 | 88
2 | 456 | null | null | 99
3 | null | 111 | 565 | 11
4 | null | 222 | null | null
5 | null | 333 | null | null
6 | null | null | 888 | null
I have basically created views (I don't know if this is the correct term for it) and tried to UNION ALL them, but this only gives me a single column with all the totals.
SELECT *
FROM
(
SELECT o.DealerId, Sum(oi.Amount) as T1_Total
FROM ....
) AS T1
UNION ALL
SELECT *
FROM
(
SELECT o.DealerId, Sum(oi.Amount) as T2_Total
FROM ....
) AS T2
UNION ALL
...
-- repeat for T3 and T4
You can also use the pivot operator:
select dealerId, T1, T2, T3, T4
from (
select dealerId, 'T1' as Src, "t1 Total Amount" as Amt from T1
union all
select dealerId, 'T2' , "t2 Total Amount" from T2
union all
select dealerId, 'T3' , "t3 Total Amount" from T3
union all
select dealerId, 'T4' , "t4 Total Amount" from T4
) vert
pivot (sum(Amt) for Src in (T1,T2,T3,T4)) horiz
Results:
dealerId T1 T2 T3 T4
----------- ----------- ----------- ----------- -----------
1 123 NULL 555 88
2 456 NULL NULL 99
3 NULL 111 565 11
4 NULL 222 NULL NULL
5 NULL 333 NULL NULL
6 NULL NULL 888 NULL
Try doing something like this:
with all_dealer_ids AS (
SELECT DISTINCT dealerId
FROM Table1
UNION
SELECT DISTINCT dealerId
FROM Table2
UNION
SELECT DISTINCT dealerId
FROM Table3
UNION
SELECT DISTINCT dealerId
FROM Table4
)
SELECT adi.dealerId, SUM(t1.TotalAmount) As T1TotalAmount, SUM(t2.TotalAmount) As
T2TotalAmount, SUM(t3.TotalAmount) AS T3TotalAmount, SUM(t4.TotalAmount) AS T4TotalAmount
FROM all_dealer_ids adi
LEFT JOIN Table1 t1
ON adi.dealerId = t1.dealerId
LEFT JOIN Table2 t2
ON adi.dealerId = t2.dealerId
LEFT JOIN Table3 t3
ON adi.dealerId = t3.dealerId
LEFT JOIN Table4 t4
ON adi.dealerId = t4.dealerId
GROUP BY adi.dealerId
ORDER BY adi.dealerId ASC
You'll want to use JOIN instead of UNION to accomplish what you're looking for. UNIONs are typically used to stack data, which is why you are seeing all your data in one column. You can try something like this to accomplish what you are looking for.
SELECT COALESCE(t1_totals.dealerID, t2_totals.dealerID, t3_totals.dealerID, t4_totals.dealerID) AS dealerId
, t1_totals.t1_total_amount
, t2_totals.t2_total_amount
, t3_totals.t3_total_amount
, t4_totals.t4_total_amount
FROM (
SELECT dealerID, sum(amount) AS t1_total_amount FROM t1 GROUP BY t1.dealerID
) AS t1_totals
FULL JOIN (
SELECT dealerID, sum(amount) AS t2_total_amount FROM t2 GROUP BY t2.dealerID
) AS t2_totals
ON t2_totals.dealerID = t1_totals.dealerID
FULL JOIN (
SELECT dealerID, sum(amount) AS t3_total_amount FROM t3 GROUP BY t3.dealerID
) AS t3_totals
ON t3_totals.dealerID = t1_totals.dealerID
FULL JOIN (
SELECT dealerID, sum(amount) AS t4_total_amount FROM t4 GROUP BY t4.dealerID
) AS t4_totals
ON t4_totals.dealerID = t1_totals.dealerID
ORDER BY dealerId

SQL Server Join 2 Tables with Relationship in 3rd Table

I have 3 tables:
Table_A
tblA_ID | tblA_Key | tblA_Info
1 2A ABC
Table_B
tblB_ID | tblB_to_A_Relations | tblB_Info
1 1 XYZ
2 1 DEF
3 1 QWE
4 1 NOP
Table_C
tblC_ID | tblC_to_A_Relations | tblC_Info
1 2A 999
2 2A 888
3 2A 777
Table_B and Table_C doesn't have direct relationship but I wanted to join them by using their relationships on Table_A. This is what I've tried so far.
SELECT DISTINCT
b.*,
c.tblC_Info,
FROM Table_B b
LEFT JOIN (SELECT tblA_ID, tblA_Key FROM Table_A
WHERE tblA_Key = #parameter)a
ON a.tblA_ID = b.tblB_to_A_Relations
LEFT JOIN Table_C c
ON c.tblC_to_A_Relations = a.tblA_Key
ORDER BY b.tblB_ID ASC
Somehow outputs:
ResultSet
tblB_ID | tblB_to_A_Relations | tblB_Info | tblC_Info
1 1 XYZ 999
1 1 XYZ 888
1 1 XYZ 777
2 1 DEF 999
2 1 DEF 888
2 1 DEF 777
3 1 QWE 999
3 1 QWE 888
3 1 QWE 777
4 1 NOP 999
4 1 NOP 999
4 1 NOP 999
But my expected output is something like this:
ExpectedOutput
tblB_ID | tblB_to_A_Relations | tblB_Info | tblC_Info
1 1 XYZ NULL
2 1 DEF 999
3 1 QWE 888
4 1 NOP 777
Surely missing something. Any help would really be appreciated!
EDIT
After more inspection of the existing tables and data, it appears that the above results are already filtered records and luckily, after tedious tracing, I found a field that somehow tells them they are unique from the other records.
Table_B
tblB_ID | tblB_to_A_Relations | tblB_Info | **tblB_Values**
1 1 XYZ AAA
2 1 DEF BBB
3 1 QWE CCC
4 1 NOP DDD
Table_C
tblC_ID | tblC_to_A_Relations | tblC_Info | **tblC_Values**
1 2A 999 BBB
2 2A 888 CCC
3 2A 777 DDD
At first, I made a mistake to ignore these fields not knowing the answer was there all along.
Going to post my answer.
Declare #A table
(
tbla_ID int,
tblA_Key varchar(2),
tbla_info varchar(3)
)
Declare #B table
(
tblb_ID int,
tblB_to_A varchar(2),
tblB_info varchar(3)
)
Declare #C table
(
tblb_ID int,
tblC_to_A varchar(2),
tblB_info int
)
Insert into #A
Select 1,'2A','ABC'
Insert into #B
Select 1,1,'XYZ'
union
Select 2,1,'DEF'
union
Select 3,1,'QWE'
union
Select 4,1,'NOP'
Insert into #c
Select 1,'2A',999
UNION
Select 2,'2A',888
UNION
Select 3,'2A',777
Select B.*,C.tblB_info from #A A
join #B B
on A.tbla_ID=B.tblB_to_A
left join #C C
on B.tblb_ID=C.tblb_ID and A.tbla_key=C.tblC_to_A
Null value belongs to 4th row exactly equal to 'NOP'
The workaround I did:
Create a temporary container and update unique keys from Table_B to Table_C in a modified column of a temporary table with reference to Table_A.
Here's what the temporary table looked like:
TempTbl
tblC_ID | Modified_Col | tblC_to_A_Relations | tblC_Info
1 2 2A 999
2 3 2A 888
3 4 2A 777
Managed to get this resultset using a copy of Table_C (#TempTbl)
UPDATE #TempTbl
SET
#TempTbl.Modified_Col = #TempTbl_B.tblB_ID
FROM
#TempTbl
INNER JOIN
#TempTbl_B
ON
#TempTbl.tblB_Values = #TempTbl_B.tblC_Values
And pulled left join for final result.
SELECT * FROM Table_B x
LEFT JOIN #TempTbl y
ON x.tblB_ID = y.Modified_Col
PS: I really do apologize how horrible the workaround was.

how to select all value from two table

tableA tableB
IdPrice price id tax IdPrice
---------------------- ------------------------------------
4 100 1 20 4
------------------------ ------------------ ------------------
5 150 2 10 6
------------------------ ------------------ ------------------
6 270
------------------------
result =
price id tax
---- --- ----
100 1 20
150 2 10
270 null null
my Query
SELECT price,id,tax
FROM tableB INNER JOIN
tableA ON tableA.IdPrice= tableB.IdPrice
but this result
price id tax
---- --- ----
100 1 20
150 2 10
SELECT
a.price as price, b.id as id, b.tax as tax
FROM
tableA a
LEFT OUTER JOIN
tableB b ON a.IdPrice = b.IdPrice
Use left outer join you can get all the records from tableA.

Need select 2 rows from Table2, which is joined with Table1. See description

For example i have a Table1:
ID Specified TIN Value DateCreated
----------------------------------
1 0 tin1 45 2014-12-30
2 1 tin2 34 2013-01-05
3 0 tin3 23 2015-02-20
4 3 tin4 47 2013-06-04
5 3 tin5 12 2012-04-02
And a Table2:
ID Table1ID RegistrationDate
----------------------------------
1 1 2015-10-12
2 2 2015-07-21
3 1 2015-11-26
4 1 2015-12-04
5 2 2015-09-18
I need select all columns from Table1 with first and last RegistrationDate column in Table2. The answer should be
ID Specified TIN Value DateCreated FirstRegDate LastRegDate
---------------------------------------------------------------
1 0 tin1 45 2014-12-30 2015-10-12 2015-12-04
2 1 tin2 34 2013-01-05 2015-07-21 2015-09-18
3 0 tin3 23 2015-02-20 NULL NULL
4 3 tin4 47 2013-06-04 NULL NULL
5 3 tin5 12 2012-04-02 NULL NULL
Hi one possible solution can be something similar to pseudo query below(if you can prepare the tables I will modify to reflect actual query)
SELECT table1.*, inlineTable2.firstRegDate, inlineTable2.lastRegDate
FROM Table1
LEFT JOIN
(
SELECT
Table1ID AS id,
MIN(registrationDate) as firstRegDate,
MAX(regsitrationDate) as lastRegDate
FROM table2
GROUP BY table1ID
) AS inlineTable2
ON table1.id = inlineTable2.id
You can group by all columns in table1, and look up the minumum and maximum registration date for the group:
select ID
, Specified
, ... other columns from table1 ...
, min(RegistrationDate)
, max(RegistrationDate)
from Table1 t1
left join
Table2 t2
on t1.ID = t2.Table1ID
group by
ID
, Specified
, ... other columns from table1 ...

Compare the values of column in SQL Server

Table_1 columns are:
======================
A B
======================
100 4
-----------
101 2
101 3
101 4
-----------
102 6
-----------
103 7
-----------
104 2
104 3
104 4
-----------
105 2
-----------
106 4
-----------
107 3
--------------------------------
Now I have input B parameter like '6' or '2,3,4'.
I want to get a result like this:
if input B parameter is '6', then output should be:
======================
A B
======================
102 6
If input B parameter is '2,3,4', then output should be:
======================
A B
======================
101 2
101 3
101 4
-----------
104 2
104 3
104 4
Just select the needed columns:
SELECT A, B
FROM Table_1
WHERE B IN (2,3,4)
EDIT:
If you need them only if all params are present
SELECT A, B
FROM Table_1
WHERE A IN (SELECT A FROM Table_1 WHERE B = 2) AND A IN (SELECT A FROM Table_1 WHERE B = 3) AND A IN (SELECT A FROM Table_1 WHERE B = 4)
You can try this one, for your specific requirement -
-- the last digit after = i.e. 3 should be replaced by number of inputs in check for our case it is 3 for (2,3,4)
SELECT A,B FROM Table_1 AS tbl1 WHERE B IN (2,3,4) AND (select COUNT(1) FROM Table_1 AS tbl2 WHERE B IN (2,3,4) AND tbl1.A = tbl2.A)
= 3
Please, have a look.
Thanks!
SELECT A
,B
FROM table_1
WHERE A IN (
SELECT A
FROM table_1
WHERE B = 2
)
AND A IN (
SELECT A
FROM table_1
WHERE B = 3
)

Resources