-- 1.第一种格式:
case 列名
when 条件值1 then 选项1
when 条件值2 then 选项2.......
else 默认值 end
-- 1.第二种格式:
case
when 列名=条件值1 then 选项1
when 列名=条件值2 then 选项2.......
else 默认值 end
-- 第三种 MyBatis Mapper
<choose>
<when test="req.dimensionTypeEnum == @com.enums.DimensionTypeEnum@GROUP">,field1 as field </when>
<otherwise>,field2 as field </otherwise>
</choose>
2.排行榜SQL
--单维度排行
select the_month,
name,
sum(field1) as 数据当前值,
-- 可多字段排名(第一个值相同时可采用后续指标再排序)
rank() over (order by sum(field1) desc,name asc) as 数据当前排名,
-- lag函数 参数2:数字1代表上一名(同理:改为数字2代表前2名),参数三:上一名不存在时的默认值(此处为0 - 可根据字段数据类型自行设置精度)
lag(sum(field1), 1, 0) over(order by sum(field1) desc,name asc) as 数据上一名的值,
-- 用上一名的值减去当前值即可:lag 第二个参数:前1名,第3个参数:默认值(第一名的前一名的默认值是空)
-- 此处lag函数第三个参数 - 默认采用当前值(避免第一名找不到前一名,差值异常)
lag(sum(field1), 1, sum(field1)) over(order by sum(field1) desc,name asc) - sum(field1) as 数据当前值距上一名的差值
from table_name a
WHERE the_month = '2022-09'
group by the_month, name ;
-- 多维度排行
select the_month,
AREA_NAME,
channel,
sum(field1) as 数据当前值,
-- 当前值在 channel 字段进行分组的情况下,每一组中的排名;
rank() over ( partition by channel order by sum(field1) desc) as 各自分组中的排名
from table_name a
WHERE the_month = '2022-09'
group by the_month, name,channel