如何在UNION语句中更改列标题的名称

时间:2019-04-23 13:23:50

标签: sql union column-alias

UNION查询中的列标题被命名为第一个查询的select语句,如何将列标题更改为“实体”和“错误”?

The Query is:

SELECT DISTINCT
'1001account' as [1001account], [1001account] as '1001account' 
FROM 
XXX
WHERE
StresstestaccountEnabled LIKE '%Yes%' AND BalancesheetAmount <> 0
AND
PATINDEX('%[^0-9]%', [1001account]) > 0 OR [1001account] IS NULL

UNION

SELECT DISTINCT
'[MAX(InterestRate)]' as InterestType, MAX(InterestRate) as 'MAXInterestRate'
FROM 
XXX    
WHERE
BalanceSheetAmount <> 0
AND
StressTestAccountEnabled LIKE 'Yes'

UNION

SELECT DISTINCT
'[MIN(InterestRate)]' as InterestType, MIN(InterestRate) as 'MINInterestRate'
FROM 
XXX    
WHERE
BalanceSheetAmount <> 0
AND
StressTestAccountEnabled LIKE 'Yes'

UNION

SELECT DISTINCT
'[MAX(SwapRate)]' as [SwapRate], MAX(SwapRate) as 'MAXSwapRate'
FROM 
XXX     
WHERE
BalanceSheetAmount <> 0
AND
StressTestAccountEnabled LIKE 'Yes'

UNION

SELECT DISTINCT
'[MIN(SwapRate)]' as [SwapRate], MIN(SwapRate) as 'MINSwapRate'
FROM 
XXX    
WHERE
BalanceSheetAmount <> 0
AND
StressTestAccountEnabled LIKE 'Yes'

UNION

SELECT DISTINCT
'[MAX([Margin])]' as [Margin], MAX([Margin]) as 'MAXS[Margin]'
FROM 
XXX    
WHERE
BalanceSheetAmount <> 0
AND
StressTestAccountEnabled LIKE 'Yes'

UNION

SELECT DISTINCT
'[MIN([Margin])]' as [Margin], MIN([Margin]) as 'MIN[Margin]'
FROM 
XXX    
WHERE
BalanceSheetAmount <> 0
AND
StressTestAccountEnabled LIKE 'Yes'


OUTPUT IS:

**1001account**         **1001account**
[MAX([Margin])]         170.8372200000
[MAX(InterestRate)]         172.7691400000
[MAX(SwapRate)]         70.8750000000
[MIN([Margin])]         -70.6084500000
[MIN(InterestRate)]         -19.4163150000
[MIN(SwapRate)]         -1.0392500000
1001account                 NULL
5028account                 NULL

如您所见,列标题引用了第一个查询的select语句。如何在使用UNION语句时更改这些标头的名称?

1 个答案:

答案 0 :(得分:0)

在第一个选择中更改别名

SELECT DISTINCT
    '1001account' as Entities, [1001account] as Errors 
    FROM 
    XXX
    WHERE
    StresstestaccountEnabled LIKE '%Yes%' AND BalancesheetAmount <> 0
    AND
    PATINDEX('%[^0-9]%', [1001account]) > 0 OR [1001account] IS NULL