SQL - Is it possible to join a table to a resultset created by several select/union-alls?
-
18-03-2021 - |
Вопрос
I'm trying to find a workaround (hack) to some limitations preventing me from using a temporary table or a table variable in my SQL query.
I have a real table (technically it's a derived table that results from an UNPIVOT of a poorly designed table) which lacks several necessary fields. I need to hardcode these fields into the result until we can cleanup the database issue.
Given a table like:
tblEntity
ID | Name
1 | One
2 | Two
I need to join several fields such as:
ID | Order
1 | 2
2 | 1
The join would result in:
ID | Name | Order
1 | One | 2
2 | Two | 1
My question is: can I join tblEntity to a resultset created like:
SELECT 1, 2
UNION ALL
SELECT 2, 1
Is it possible to join? If so, what is the syntax?
Решение
select te.*, t.Ord from tblEntity te
inner join (
SELECT 1 as Id, 2 as Ord
UNION ALL
SELECT 2, 1
) t on te.ID = t.Id
Другие советы
Making a few assumptions, this would do it:
SELECT en.ID, en.Name, xx.OrderBy
from tblEntity en
inner join (select 1 Id, 2 OrderBy
union all
select 2,1) xx
on xx.Id = en.ID
In SQL-Server 2008, it's also possible to use Table Value Constructors
:
CREATE TABLE #tblEntity
( ID INT
, Name CHAR(10)
) ;
INSERT INTO #tblEntity
(ID, Name)
VALUES
( 1, 'One' ) ,
( 2, 'Two' ) ;
SELECT
t.ID, t.Name, o.Ordr AS "Order"
FROM
#tblEntity AS t
JOIN
( VALUES
(1,2)
, (2,1)
) AS o(ID, Ordr)
ON o.ID = t.ID ;
You can test the above in: data.stackexchange.com
Many ways of doing this e.g.
WITH T1 (Id, "Order")
AS
(
SELECT 1, 2
UNION ALL
SELECT 2, 1
)
SELECT e.*, T1."Order"
FROM tblEntity e
JOIN T1
ON e.Id = T1.Id;
e.g. 2
SELECT e.*, T1."Order"
FROM tblEntity e
JOIN (
VALUES (1, 2),
(2, 1)
) AS T1 (Id, "Order")
ON e.Id = T1.Id;
e.g. 3
WITH T1
AS
(
SELECT *
FROM (
VALUES (1, 2),
(2, 1)
) AS T (Id, "Order")
)
SELECT e.*, T1."Order"
FROM tblEntity e
JOIN T1
ON e.Id = T1.Id;
...and so on.