I am trying to convert this query to using dynamic columns (from another table). In this example I want to replace the 2 areas where I have type='comm' and type = 'exch' to be dynamic. (not hardcoded in this line) The types will be found in another table.
HERE IS MY ORIGINAL QUERY
select [date], id,
max(case when type='comm' then currency end) as Comm_cur,
max(case when type='exch' then currency end) as Exch_cur
from myTable
group by [date], id;
HERE IS THE TABLE I WANT TO USE FOR THE 'TYPE'
insert into #fm (type) values
('comm')
,('exch')
when I google this concept I get dynamic pivot tables as possible solutions but that doesn't see what I am looking to do.
source table
| date | id | type | currency |
|---|---|---|---|
| 20230112 | 1 | comm | usd |
| 20230112 | 1 | exch | usd |
| 20230119 | 2 | comm | usd |
| 20230119 | 2 | exch | gbp |
result table
| date | id | comm cur | exch cur |
|---|---|---|---|
| 20230112 | 1 | usd | usd |
| 20230112 | 2 | usd | gbp |
any help would be greatly appreciated!
Dynamic cross tabon this site and you will find lots of nearly identical questions with solutions.