Get decoded values in SQL Server that gets translated from other table

p5cysglq  于 2023-11-16  发布在  SQL Server
关注(0)|答案(2)|浏览(115)

I have a value in a table that's a foregin key. This returns a number which is a code => InvoiceDevice.DeviceType . That code is decoded in the Code table, at Code.CodeValue , then I can use WHERE InvoiceDevice.DeviceType = Code.CodeValue .

So for example:

  1. InvoiceDevice.DeviceType = 2
  2. Code.CodeValue at 2 = iPhone

This is no problem for one column. But how do I display the last value (iPhone) in a VIEW with 68 other columns? They need to be all translated from that code table! How would I do this for all of them?

20jt8wwn

20jt8wwn1#

I think you can try to use Pivot/Unpivot to make that. I have try with 3 Fields, like this :

SELECT *
FROM (
    SELECT Id, Field, Code.CodeValue
    FROM 
        (SELECT Id, Field1, Field2, Field3 FROM InvoiceDevice) AS sourc
        UNPIVOT (CodeId FOR Field IN (Field1, Field2, Field3)) AS unpvt
        INNER JOIN Code ON Code.Code = unpvt.CodeId
) AS unpivoted
PIVOT
(
    MIN(CodeValue)
    FOR Field IN (Field1, Field2, Field3)
) AS pvt;

But no idea about performance...

unftdfkk

unftdfkk2#

Might be that this is a simple question of JOIN ?

Not knowing your tables structure my magic crystal ball tells me you might be looking for something like this:

SELECT t.*
      ,c.* 
FROM YourTable t
INNER JOIN InvoiceDevice AS id ON t.code=id.DeviceType
INNER JOIN Code AS c ON c.CodeValue=id.CodeValue

The actual table and column names will need adaptions...

If the code entries within your tables are not unique for a given value, there might be additional columns you need to use as filters.

UPDATE

Reading your question once again it sounds like there are just two tables involved. In this case something like this should help:

SELECT id.*
      ,c.* 
FROM InvoiceDevice AS id 
INNER JOIN Code AS c ON c.CodeValue=id.CodeValue

相关问题