Search code examples
sqlprestotrino

trino cast as row case-insensitive


I have a sql like this

select
    cast (cast("cf00a399af"."2be9fc3823" as json) as row(cityId bigint, city varchar)) as 
    address,
    count(0) as num
from  ygg_dev."913852142333198336" cf00a399af
group by "cf00a399af"."2be9fc3823"

and my result is this

address num
{cityid=44, city=石家庄市} 1
{cityid=23, city=天津市} 1
{cityid=1318, city=泉州市} 1
{cityid=0, city=} 9
{cityid=1274, city=福州市} 1
{cityid=1318, city=泉州市} 1
{cityid=2, city=北京市} 1
{cityid=1318, city=泉州市} 2

the result cityid is a lowercase letter but i want it case-insensitive with cityId how could i do ?

the java object

@Data
public class AddressInputValue implements java.io.Serializable{

    private static final long serialVersionUID = 1L;

    @ApiModelProperty("省ID")
    private long provinceId;

    @ApiModelProperty("省名称")
    private String province;

    @ApiModelProperty("市ID")
    private long cityId;

    @ApiModelProperty("市名称")
    private String city;

    @ApiModelProperty("县ID")
    private long countyId;

    @ApiModelProperty("县名称")
    private String county;

    @ApiModelProperty("详细地址")
    private String address;

    @ApiModelProperty("经纬度坐标")
    private MapPoint point;
}

Solution

  • "By default" row field names as columns are case insensitive:

    select r.cityId c1, r.CITYID c2, r.cityid c3
    from (select cast(row(1, 'cityname') as row(cityId bigint, city varchar)) r) ;
    

    Output:

    c1 c2 c3
    1 1 1

    UPD

    If you want to have case-sensitive output - convert it to map of jsons:

    select map(array['cityId', 'city'], array[cast(r.cityId as json), cast(r.city as json)])
    from (select cast(row(1, 'cityname') as row (cityId bigint, city varchar)) r);
    

    Output:

    _col0
    {city="cityname", cityId=1}

    Additionally you can convert the whole map to json:

    select cast(
        map(array['cityId', 'city'], array[cast(r.cityId as json), cast(r.city as json)])
        as json)
    from (select cast(row(1, 'cityname') as row(cityId bigint, city varchar)) r);
    

    Output:

    _col0
    {"city":"cityname","cityId":1}