简体   繁体   English

更改查询以使用基于另一个表的动态列 - 使用条件聚合

[英]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 ID type类型 currency货币
20230112 20230112 1 1个 comm通信 usd美元
20230112 20230112 1 1个 exch交换 usd美元
20230119 20230119 2 2个 comm通信 usd美元
20230119 20230119 2 2个 exch交换 gbp英镑

result table结果表

date日期 id ID comm cur通讯电流 exch cur外汇
20230112 20230112 1 1个 usd美元 usd美元
20230112 20230112 2 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)
①如果本文未解决您的问题,请点击查看与本文相关的问题
②如果本文未解决您的问题,请向程序员专用AI小助手提问

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM