在同一选择内使用DB2列别名

时间:2019-01-02 20:48:52

标签: sql db2

我有一个有效的查询,但是我试图使用列别名以便在我的选择中创建更多计算,并且它说找不到该列(即它不能使用别名)。

例如,工作查询:

select employee,
       sum(case when date_field between '2018-01-01' and '2018-01-31' and category = 'CategoryOne' then salesprice else 0 end) as priorDate,
       sum(case when date_field between '2018-01-01' and '2018-01-31' then salesprice else 0  end) as priorTotal,
       cast(Round((DEC(sum(case when date_field between '2018-01-01' and '2018-01-31' and category = 'CategoryOne' then salesprice else 0 end),12,2)/sum(case when date_field between '2018-01-01' and '2018-01-31' then salesprice else 0  end)) * 100,2) as decimal(12,2)) as priorPercent,
       sum(case when date_field between '2019-01-01' and '2019-01-31' and category = 'CategoryOne' then salesprice else 0 end) as currentDate,
       sum(case when date_field between '2019-01-01' and '2019-01-31' then salesprice else 0 end) as currentSales,
       cast(Round((DEC(sum(case when date_field between '2019-01-01' and '2019-01-31' and category = 'CategoryOne' then salesprice else 0 end),12,2)/sum(case when date_field between '2019-01-01' and '2019-01-31' then salesprice else 0  end)) * 100,2) as decimal(12,2)) as currentPercent
from table
group by employee;

但是对于我的两个百分比(以强制转换开头的两行),我尝试仅使用priorDate / priorTotal,但是它不起作用,因此我必须将整个2个计算重复一个百分比。

我还想获得百分比差异,通过使用别名来声明它会容易得多,也许性能更高?

1 个答案:

答案 0 :(得分:1)

您可以使用CTE /子查询编写此代码:

---
published: true
title: Embeded SVG
---
## title

<svg width="400" height=300>
    <circle cx="150" cy="100" r="10" fill="blue"/>
</svg>