Is there a way to write a query that returns a value from a different row in the same table based on a value in a row and have it return that value on the same row?
I have a table with columns SC_CODE
, SC_DESC
, SC_ALT_CODE
, and SC_CANX_CODE
:
SC_CODE
values are 1
, 2
, 901
, 902
, etc. SC_DESC
values are Test1
, Test2
, Test3
, Test4
, etc. SC_ALT_CODE
values are NULL
, 3
, 4
, NULL
, etc. SC_CANX_CODE
values are 901
, 902
, 903
, 904
, etc. My query needs to return something like:
1, Test1, NULL, 901, Test3
2, Test2, 3, 902, Test4
Here, Test3
is the SC_DESC
of SC_CODE 901
and Test4
is the SC_DESC
of SC_CODE 902
, etc.
I think this should work for you:
DECLARE @TEST AS TABLE
(
SC_CODE INT
, SC_DESC VARCHAR(255)
, SC_ALT_CODE INT
, SC_CANX_CODE INT
)
INSERT @TEST (SC_CODE, SC_DESC, SC_ALT_CODE, SC_CANX_CODE)
VALUES (1, 'Test1', NULL, 901)
, (2, 'Test2', 3, 902)
, (901, 'Test3', 4, 903)
, (902, 'Test4', NULL, 904)
, (3, 'Test5', NULL, NULL)
SELECT T.SC_CODE
, T.SC_DESC
, T.SC_ALT_CODE
, T.SC_CANX_CODE
, T2.SC_DESC AS CANX_DESC
, T3.SC_DESC AS ALT_DESC
FROM @TEST AS T
JOIN @TEST AS T2
ON T2.SC_CODE = T.SC_CANX_CODE
LEFT JOIN @TEST AS T3
ON T3.SC_CODE = T.SC_ALT_CODE
Result:
+---------+---------+-------------+--------------+-----------+----------+
| SC_CODE | SC_DESC | SC_ALT_CODE | SC_CANX_CODE | CANX_DESC | ALT_DESC |
+---------+---------+-------------+--------------+-----------+----------+
| 1 | Test1 | NULL | 901 | Test3 | NULL |
| 2 | Test2 | 3 | 902 | Test4 | Test5 |
+---------+---------+-------------+--------------+-----------+----------+
Edit Added a join for SC_ALT_CODE as asked in comment. Note I added a row to the sample data to get result. Also note the use of LEFT JOIN
, not every record has an Alternative. With LEFT JOIN
you don't loose those records.
Its still not entirely clear what you are trying to do but I think you are looking for the LEAD function with an offset of 2, to produce the desired result:
CREATE TABLE #tbltmp(
SC_CODE int,
SC_DESC varchar(5),
SC_ALT_CODE int,
SC_CANX_CODE int);
INSERT INTO #tbltmp values
(1,'Test1',NULL,901),
(2,'Test2',3,902),
(901,'Test3',4,903),
(902,'Test4',NULL,904);
SELECT
SC_CODE,
SC_DESC,
SC_ALT_CODE,
SC_CANX_CODE,
LEAD(SC_DESC,2) OVER (ORDER BY SC_DESC) SC_DESC
FROM #tbltmp
DROP TABLE #tbltmp
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.