转自:http://www.cnblogs.com/keguangqiang/p/4535046.html
听说这题难住大批高手,你也来试下吧。ps:博问里的博友提出的。
原始数据
select * from t_jeff t
简单排序后数据
select * from t_jeff t order by t.VINNumber,t.channelid desc
需求,根据VINNumber分组(每对连接一起) ,再根据ChannelID倒序
1、VINNumber同组的放一起
2、组之间排序逻辑:按照每组ChannelID最大值 倒序
3、组内排序:按照ChannelID倒序。
2、组之间排序逻辑:按照每组ChannelID最大值 倒序
3、组内排序:按照ChannelID倒序。
结果需要排列如图
创建脚本
-
CREATE TABLE t_jeff (id int NOT NULL,VINNumber varchar(255) DEFAULT NULL,ChannelID varchar(255) DEFAULT NULL,TimeStamp datetime DEFAULT NULL,PRIMARY KEY (id)) ;INSERT INTO t_jeff VALUES ('1', 'Group3', '3', '2015-05-27 00:00:00');INSERT INTO t_jeff VALUES ('2', 'Group2', '5', '2015-05-23 00:00:00');INSERT INTO t_jeff VALUES ('3', 'Group1', '4', '2015-05-25 00:00:00');INSERT INTO t_jeff VALUES ('4', 'Group2', '3', '2015-05-29 00:00:00');INSERT INTO t_jeff VALUES ('7', 'Group1', '2', '2015-05-30 00:00:00');
怎么样,有思路吗
select max_channel_in_group,id, vinnumber, channelid, timestamp from ( select id, vinnumber, channelid, timestamp, max_channel_in_group = max(channelid) over(partition by vinnumber) from t_jeff ) t order by max_channel_in_group desc,channelid desc