I am looking for advice on the best way to join using an alias instead of the original data. e.g the data is modified before it is joined.
An example:
CREATE TABLE Table1 (
No1 varchar(10)
);
CREATE TABLE Table2 (
No1 varchar(10)
);
INSERT INTO Table1 (No1)
VALUES ('222');
INSERT INTO Table2 (No1)
VALUES ('111');
If i created a join with a case statement but i wanted to join on the alias of the case statement this doesnt work with usual join syntax e.g.
SELECT
CASE WHEN T1.[No1] = '222' THEN '111' ELSE T1.[No1] END AS [T1 No],
T2.[No1] AS [T2 No]
FROM Table1 T1
FULL JOIN Table2 T2
ON T1.[No1] = T2.[No1]
This gives result:
| T1 No | T2 No |
|--------+--------|
| 111 | (null) |
| (null) | 111 |
http://www.sqlfiddle.com/#!18/203e8/1
However, the approach i have taken to join on the alias is:
SELECT
T1.[T1 No],
T2.[No1] AS [T2 No]
FROM
(
SELECT
CASE WHEN T1.[No1] = '222' THEN '111' ELSE T1.[No1] END AS [T1 No]
FROM Table1 T1
) T1
JOIN Table2 T2
ON T1.[T1 No] = T2.[No1]
This gives result:
| T1 No | T2 No |
|-------+-------|
| 111 | 111 |
http://www.sqlfiddle.com/#!18/5fd7c/14
Which is exactly what i am looking for. However, the real life query i am dealing with is huge and sub-querying it to join on an alias makes it so messy.
Can anyone give me advice on a better approach to this? or is this the only way to do it?