[英]change query to use dynamic columns based on another table - with conditional aggregation
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.
在此示例中,我想将 type='comm' 和 type = 'exch' 的 2 个区域替换为动态区域。 (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.当我用谷歌搜索这个概念时,我得到了动态 pivot 表作为可能的解决方案,但这并没有看到我想要做什么。
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 columns require Dynamic SQL动态列需要 Dynamic SQL
Here is a working option that will also filter the source table based on your #fn
这是一个工作选项,它还将根据您的
#fn
过滤源表
Note: If not 2017+, you can replace the string_agg()
with the stuff/xml
approach.注意:如果不是 2017+,您可以将
string_agg()
替换为stuff/xml
方法。
Example例子
Declare @SQL varchar(max) = '
Select *
From (
Select A.date
,A.id
,type = A.type+'' cur''
,A.currency
From YourSourceTable A
Join #fn B on A.type=B.type
) src
Pivot ( max(currency) for [type] in (' + (select string_agg(quotename(type+' cur'),',') from #fn ) + ') ) pvt
'
Exec(@SQL)
Results结果
date id comm cur exch cur
2023-01-12 1 usd usd
2023-01-19 2 usd gbp
Just in case you need the stuff/XML以防万一你需要东西/ XML
Declare @SQL varchar(max) = '
Select *
From (
Select A.date
,A.id
,type = A.type+'' cur''
,A.currency
From YourSourceTable A
Join #fn B on A.type=B.type
) src
Pivot ( max(currency) for [type] in (' + stuff((Select Distinct ',' +quotename(type+' cur') From #fn For XML Path ('')),1,1,'') + ') ) pvt
'
Exec(@SQL)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.