1,一行转多行
url列以分号分隔,将其一行转化为多行,借助自增长表help_topic 实现。
select a.channel_id,channel_code,site_name,siteid,refer_channel,substring_index(substring_index(a.url,';',b.help_topic_id+1),';',-1) as urls from t_channel_mapping a join mysql.help_topic b on (length(a.url) - length(replace(a.url,';',''))+1) > b.help_topic_id;
2,多行转一行
分组后汇总成一行,orderid以逗号分隔
select SiteID,group_concat(distinct cast(orderid as char(8))) as orderid from site_order
3,MYSQL实现rownumber
mysql是不支持rownum函数,下面例子实现产品表中给产品一个顺序编号
select @rownum:=@rownum+1 rownum, product
from
(
select (@rownum:=0),a.product
from
(select product from t_proudct_info GROUP BY product) a
) t
4, MYSQL实现FIRST_VALUE(t.url) over(partition by siteid,refer_channel)
mysql中没有类似oracle和postgreSQL的 OVER(PARTITION BY)功能,如下实现查询每个分组中按url排序后第一个url
select siteid,refer_channel,substring_index(group_concat( t.url ),',',1)
from (
select siteid,refer_channel,url from t_channel_mapping order by siteid,refer_channel,url
) t group by siteid,refer_channel
5,MYSQL常用日期函数
MySQL Date/Time to Str(日期/时间转换为字符串)函数:date_format(date,format), time_format(time,format)
select date_format('2008-08-08 22:23:01', '%Y%m%d%H%i%s');
20080808222301
MySQL Str to Date (字符串转换为日期)函数:str_to_date(str, format)
select str_to_date('08/09/2008', '%m/%d/%Y'); -- 2008-08-09
select str_to_date('08/09/08' , '%m/%d/%y'); -- 2008-08-09
select str_to_date('08.09.2008 08:09:30', '%m.%d.%Y %h:%i:%s'); -- 2008-08-09 08:09:30
date_add()函数向日期添加指定的时间间隔。
DATE_ADD(OrderDate,INTERVAL 2 DAY)
DATE_ADD(OrderDate,INTERVAL -2 MONTH)
DATEDIFF() 函数返回两个日期之间的天数。
SELECT DATEDIFF('2008-12-30','2008-12-29') AS DiffDate
更多sql技术请关注 http://www.w3school.com.cn/sql/