首页 > 解决方案 > 如何将两个选择结果并排放在列中?

问题描述

每个人!我有一个查询,它计算一段时间内某个 KPI 的平均值,并按资产名称对其进行分组。但是,我为每个资产设置了 10 个指标,并希望并排显示查询结果,如下所示:

ASSET         Ind_X01   Ind_X02   Ind_X03  ...  Ind_X10
Asset01         10         25       21%    ...    46 
Asset02         15         15       25%    ...    10
Asset03         84         08       73%    ...    00
...
Asset_N         74         89       50%    ...    87

我为每个资产的指标做了一个查询,但我找不到将它们并排连接在一起的方法,如上所示。我只有独立的查询,每一个都有一列:

查询 01 读取指标 01:

ASSET         Ind_X01  
Asset01         10       
Asset02         15     
Asset03         84     
...
Asset_N         74  

查询 02 读取指标 02:

ASSET         Ind_X01  
Asset01         10       
Asset02         15     
Asset03         84     
...
Asset_N         74  

等等...

我正在使用的查询是下面的查询,通过更改 IndicatorName 我可以为其他查询运行:

local IndicatorName char(3);

IndicatorName = 'X01';

MACRO ColumnTitle = 'Ind_'||IndicatorName;

select ASSETS, avg(IND_CALCS) as &ColumnTitle from DB
where 
    DB_KPI_NAME = IndicatorName and
    DB_DATETIME between cast('2020-08-08 19:00:00.0' as timestamp format 'YYYY-MM-DD HH:MI:SS.T') and cast('2020-08-10 23:59:59.0' as timestamp format 'YYYY-MM-DD HH:MI:SS.T')
group by ASSETS

你们能帮我解决这个问题吗?谢谢。

标签: sql

解决方案


我想你想要这样的东西:

select ASSETS,
       avg(case when indicatorname = 'X01' then IND_CALCS end) as ind_X01,
       avg(case when indicatorname = 'X02' then IND_CALCS end) as ind_X02,
       avg(case when indicatorname = 'X03' then IND_CALCS end) as ind_X03,
       . . . 
from DB
where DB_DATETIME between cast('2020-08-08 19:00:00.0' as timestamp format 'YYYY-MM-DD HH:MI:SS.T') and cast('2020-08-10 23:59:59.0' as timestamp format 'YYYY-MM-DD HH:MI:SS.T')
group by ASSETS;

推荐阅读