如何在SQL中与分组依据一起使用时“选择大小写”

目标是“编写一个SQL查询,该查询计算2016年的write_premium_dollar_amount总量和2017年的write_premium_dollar_amount总量。”

表示例为:

Enter sales for day
>22.45
Enter sales for day
>3.78
Enter sales for day
>47.39
Enter sales for day
>9.48
Enter sales for day
>22.45


You get a commission of 25$
Maximum sales on Wednesday is $47.39
Minimum sales on Tuesday is $3.78
Total weekly sales were $105.55000000000001
Average of the sales is $21.110000000000003

我写了一个查询:

id  state  exposure_month  written_premium_dollar_amount
1    OH     201606                 104  
1    OH     201606                 50   
2    OH     201703                 13.34
`
`
`   

结果是

select exposure_month,sum(written_premium_dollar_amount) as totalWrittenPremium
from finacials 
where exposure_month like '2016%' 
or exposure_month like '2017%' 
group by exposure_month

现在,我想按年对总保费进行分组。我写的代码是:

exposure_month  totalWrittenPremium
201606              154
201608              99
201609              93
201610              0.2
201612              211.55
201701              37.88
201702              114
201703              163 
`
`
`

我收到一个错误无效的列名'exposure_year'。 我知道Exposure_year不能成为分组条件,因为原始表中不存在Exposure_year colunm。另外,我不能说*。因此,我的问题是:

  1. 有什么办法可以实现我的目标?
  2. 是否可以将Exposure_year添加到原始表中,并按Exposure_year使用组?如果有效,我该怎么办?
wangyipangli 回答:如何在SQL中与分组依据一起使用时“选择大小写”

嗨,尝试使用如下查询。

select exposure_month,sum(written_premium_dollar_amount) as totalWrittenPremium
from finacials 
where exposure_month like '2016%' 
or exposure_month like '2017%' 
group by  left(exposure_month,4)
,

查询。

select case when left(exposure_month,4)='2016' then '2016'
            when left(exposure_month,4)='2017' then '2017'
            else 'others'
       end exposure_year,sum(written_premium_dollar_amount) as totalWrittenPremium
from finacials
group by case when left(exposure_month,4)='2016' then '2016'
              when left(exposure_month,4)='2017' then '2017'
              else 'others'
         end
本文链接:https://www.f2er.com/3169040.html

大家都在问