手術テーブル: ユーザー
テーブルデータ:
要件: セックス フィールドを年齢別にランク付けする必要があります。若いものを前に、年上のものを後ろにします。
1. SQL ステートメントを使用してクエリ結果にシリアル番号を追加します。
ソートしたデータをSQLで加工し、別途シリアル番号を付加する方法です。
// (SELECT @i:=0)j 声明一个变量(注意,如果声明的变量是关键字则会异常),变量初始值为 0,每次让它+1
// 声明一个变量 (@i:=@i+1)"字段”
SELECT (@i:=@i+1)"序号", u.* FROM 表名 u,(SELECT @i:=0)j
例外宣言方法:rankコマンドは使用できません
SELECT (@i:=@i+1)"序号", u.* FROM user u,(SELECT @i:=0)rank
- 例1: ソートされていない目標値
ここからわかるように、シリアル番号はすでに存在していますが、性別フィールドはまだ処理されていません。
- 例 2: ターゲットを処理してからシーケンス番号を追加する
性別がソートされ、ランキング フィールドとしてシリアル番号も使用されていることがわかります (この方法は比較的単純ですが、以下にさらに高度な方法があります)。
2. 性別に応じてシリアル番号を増やし、同性で結びます
select c.* ,ifnull((
select count(*) from
(select * from user order by sex ) as b
where c.sex > b.sex
),0)+1 as rownum from
(select * from user order by sex ) as c
効果は次のとおりです。
小さいものを最後に、大きいものを最初にランク付けしたい場合は、それを未満に変更します。
効果は次のとおりです。
3. コレクションを使用してこれらのデータを処理用に受け取ります
public static void main(String[] args) {
// BigDecimal类型
ArrayList<User> list = new ArrayList<>();
list.add(new User(1,"myqxin","1234",11,null,null));
list.add(new User(2,"zfwy","4353",12,null,null));
list.add(new User(3,"qyls","6145",17,null,null));
list.add(new User(4,"ly","2342",12,null,null));
list.add(new User(5,"bl","2532",13,null,null));
List<User> users = mergerList(list);
for (User user : users) {
System.err.println(user);
}
}
public static List<User> mergerList(List<User> list){
//list降序排序
List<User> collect = list.stream().sorted(Comparator.comparing(User::getSex)).collect(Collectors.toList());
//翻转list
Collections.reverse(collect);
Integer index=1;
Integer maxScore=0;
for (int i = 0; i < list.size(); i++) {
if (i==0){
collect.get(i).setRanking(index);
maxScore=collect.get(i).getSex();
}else if (Objects.equals(collect.get(i).getSex(),maxScore)){
collect.get(i).setRanking(index);
}else {
index++;
collect.get(i).setRanking(index);
maxScore=collect.get(i).getSex();
}
}
return collect;
}
効果は次のとおりです。
上記のランキングと比較すると、上記はプレースホルダーです。これらを順番に並べると、同じプレースホルダーは存在しません。
4. オブジェクトを特定の属性値でランク付けし、同じ値を持つオブジェクトを結び付けます。
public static List<ExcellentRanking> mergerList(List<ExcellentRanking> list) {
if (list.size() < 1) {
return new ArrayList<ExcellentRanking>();
}
ArrayList<ExcellentRanking> restwo = new ArrayList<>();
// 对需要排名的值做了处理
for (ExcellentRanking airQualityRankingResp : list) {
if (airQualityRankingResp.getValue() == null) {
airQualityRankingResp.setValue(0.0);
restwo.add(airQualityRankingResp);
} else {
restwo.add(airQualityRankingResp);
}
}
//list降序排序
List<ExcellentRanking> collect = restwo.stream().sorted(Comparator.comparing(ExcellentRanking::getValue)).collect(Collectors.toList());
//翻转list
Collections.reverse(collect);
for (ExcellentRanking airQualityRankingResp : restwo) {
int index = 1;
for (ExcellentRanking airQualityRankingResp1 : collect) {
// > 值越小排名越靠前 < 值越大排名越靠前
if (airQualityRankingResp.getValue() < airQualityRankingResp1.getValue()) {
index++;
}
}
airQualityRankingResp.setRanking(index);
}
return restwo;
}
効果: