SQL常见问题及解决

1、max()函数,对于某一个认为是数值型但实际是字符型字段取最大值,采用max函数,发现结果一直有错,如9>13.

  解决方法:在max括号里面加一个0,把这个字段转化为数值型再进行比较,select max(a+0)

2、时间处理,日期取年月日,时间戳取日期,日期格式转化等等需求,经常会出现各种问题

  解决方法:先百度下用什么用什么函数来转,在正式跑数前,直接用select函数a来测试下

  一种特殊的日期处理是北京时间和Unix时间转换,代码如下:

  select from_unixtime(time),select from_unixtime(cast(substr(time,1,10)as int))

3、先聚合再计数,如果要计算某个维度下的用户数,不要直接算用户数count(distinct imei),而应该是如下代码:

  select city,count(1) as uv from (select city,imei,count(1) from a group by city,imei)t1 group by city

4、一列变多行,ab测试中会对一个用户打很多标签,而这些标签都是存在一个字段中,所以要看维度指标,要对该字段进行列变行拆解,代码如下:

  select *,b from t1 Lateral view explode(a) table as b

5、取top,要看某分类下的top10消费额子分类(金额一致就并列),代码如下:

  select *,rank()over(partition by a order by b desc) as rank from table t1

6、避免数据倾斜,小表在左,大表在右,使用map join,同时对空值进行过滤,代码如下:

  select /*+mapjoin(a)*/ t1.city,t2.type,count(t1.imei) as uv 

  from 

  (select city,imei,count(1) as pv  from a where imei !='' group by city,imei)t1

  join 

  (select type,imei,count(1) as pv  from a where imei !='' group by city,imei)t2

  on t1.imei=t2.imei

  group by t1.city,t2.type

猜你喜欢

转载自www.cnblogs.com/xiao02fang/p/13194877.html