tags:

views:

16

answers:

1

I'm combining these 3 tables into a report query with INNER JOINs (this is a simplified example):

USERS
ID    NAME    CODE1    CODE2
1     James   c1_2     c2_3
2     Bob     c1_3     c2_1

C1
CODE1     VALUE
c1_1      interested
c1_2      maybe
c1_3      not interested

C2
CODE1     VALUE
c2_1      prepared
c2_2      self-study
c2_3      novice

The query result looks like this:

NAME     INTEREST          PREPARED
James    maybe             novice
Bob      not interested    prepared

I would like to get rid of the lookup tables and create this query result using only the USERS table and probably some clever REPLACE() statement. Can it be done?

Thank you!

A: 

Sure but I don't see the point.

SELECT  u.Name, c1.Value, c2.Value
FROM    dbo.Users u
        INNER JOIN (
          SELECT 'c1_1' as Code1, 'interested' as Value
          UNION ALL SELECT 'c1_2', 'maybe'
          UNION ALL SELECT 'c1_3', 'not interested'
        ) c1 ON c1.Code1 = u.Code1
        INNER JOIN (
          SELECT 'c2_1' as Code1, 'prepared' as Value
          UNION ALL SELECT 'c2_2', 'self-study'
          UNION ALL SELECT 'c2_3', 'novice'
        ) c2 ON c2.Code1 = u.Code2

ps. I know this is (most likely) not what you mean but my guestimate is that it will always outperform any REPLACE solution and is more flexible.

Lieven
This is exaclty what I needed! I thought replace was the only option, but this is much nicer.I needed this because I had a couple dozen tables like C1, C2 - and they were only needed for one select query to convert codes to human readable values. These tables only crowded the database, now I don't need them anymore.Many thanks!
Enorog