i want to show to the sec query result in to first queyy last column in sql.commen

i want to show to the sec query result in to first queyy last column in sql.commen

Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Tuhin PaulPosted Jan 15, 2025, 5:49 PM
RankedTable1:ROW_NUMBER()function toTable_1based on theSettings_COTcolumn (you can adjust the ordering based on your requirement). This assigns a unique row number (RowNum1) to each record for a givenYear.PARTITION BY Yearclause so that the row numbers are reset for each year.RankedTable2:ROW_NUMBER()function is applied toTable_2based on thePerApp_Potcolumn (again, you can adjust ordering criteria). This assigns a unique row number (RowNum2) to each record for a givenYear.Sreenath KappoorPosted Jan 14, 2025, 12:03 PM
Hi Lejo,
CREATE TABLE Table_1 (
Year INT,
Settings_COT VARCHAR(50),
Settings_DOT VARCHAR(50),
Settings_POT VARCHAR(50),
Monitoring_COT VARCHAR(50),
Monitoring_DOT VARCHAR(50),
);
CREATE TABLE Table_2 (
Year INT,
PerApp_Pot VARCHAR(50)
);
INSERT INTO Table_1 (Year, Settings_COT, Settings_DOT, Settings_POT, Monitoring_COT, Monitoring_DOT)
VALUES (2025, 'DIYAR [2501-86]', 'Finance [2501-87]', '2501-88 [2]', NULL, NULL);
INSERT INTO Table_1 (Year, Settings_COT, Settings_DOT, Settings_POT, Monitoring_COT, Monitoring_DOT)
VALUES (2025, 'DIYAR [2501-86]', 'Finance [2501-87]', '2501-98 [2]', NULL, NULL);
INSERT INTO Table_2 (Year, PerApp_Pot)
VALUES (2025, '2501-102 [2]');
INSERT INTO Table_2 (Year, PerApp_Pot)
VALUES (2025, '2501-90 [2]');
SELECT * FROM TABLE_1
SELECT * FROM TABLE_2
Join the tables
SELECT
T1.Year,
T1.Settings_COT,
T1.Settings_DOT,
T1.Settings_POT,
T1.Monitoring_COT,
T1.Monitoring_DOT,
T2.PerApp_Pot
FROM
Table_1 T1
LEFT JOIN
Table_2 T2
ON
T1.Year = T2.Year
To avoid generating 4 rows when joining the tables due to a many-to-many relationship on the Year column, you can create a one-to-one mapping by using the ROW_NUMBER() function.
WITH RankedTable1 AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY Settings_COT) AS RowNum
FROM Table_1
),
RankedTable2 AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY PerApp_Pot) AS RowNum
FROM Table_2
)
SELECT
T1.Year,
T1.Settings_COT,
T1.Settings_DOT,
T1.Settings_POT,
T1.Monitoring_COT,
T1.Monitoring_DOT,
T2.PerApp_Pot
FROM
RankedTable1 T1
LEFT JOIN
RankedTable2 T2
ON
T1.RowNum = T2.RowNum
Result: