Question

In an unpivoting operation, I would like the following:

SELECT A, B, C FROM [complex joins/where clause] As DerivedTable
UNION
SELECT A, B, D FROM DerivedTable
UNION
SELECT A, B, E FROM DerivedTable
...

but it complains that DerivedTable cannot be found (I use a derived table so that [complex joins/where clause] doesn't have to be evaluated again and again thereby slowing things).

I know I can simply create a new query called DerivedTable to represent [complex joins/where clause] but

  • The above SQL is passed from Excel - I'd rather not have to open the database to create a new query prior to running the above

  • The [complex joins/where clause] is generated dynamically, and changes from user to user, two of which may be running the above SQL at the same time.

Était-ce utile?

La solution

Something like this. Use CASE and JOIN this table with (1,2,3,...) table. I'm not sure it is right syntax for Access but it will work on most SQL dialects.

SQLFiddle demo

SELECT A,B, 
       CASE WHEN CT.r=1 then C
            WHEN CT.r=2 then D
            WHEN CT.r=3 then E
       END

FROM [complex joins/where clause] As DerivedTable
CROSS JOIN (select 1 as r
            union all  
            select 2 as r
            union all  
            select 3 as r
           ) as CT
order by A,B
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top