这是我的用户数据库:
unordered_map<string, int> word_counts;
for (const auto& str : words) {
word_counts[str]++;
}
auto cmp = [&word_counts](const string &word1, const string &word2){
auto iter = word_counts.find(word1);
int count1 = (iter != word_counts.end()) ? iter->second : 0;
iter = word_counts.find(word2);
int count2 = (iter != word_counts.end()) ? iter->second : 0;
/* or, throw an exception if word1 or word2 are not found...
int count1 = word_counts.at(word1);
int count2 = word_counts.at(word2);
*/
if (count1 == count2)
return word1 < word2;
return count1 > count2; // <-- why > and not < ?
};
我使用以下查询来返回:
(1)趋向女性
(2)其余女性
(3)男性趋向
(4)其余男性
id | sex | trending | date_registered
---+--------+----------+----------------
1 | male | 1 | 29-04-2020
2 | male | 1 | 28-04-2020
3 | male | 0 | 27-04-2020
4 | female | 1 | 26-04-2020
5 | female | 1 | 25-04-2020
6 | female | 0 | 24-04-2020
7 | female | 0 | 23-04-2020
8 | male | 1 | 22-04-2020
9 | male | 0 | 21-04-2020
最重要的是,我首先要针对每个case-when语句按最新用户进行排序。
例如select
id,
sex,
trending,
date_registered
from users
order by
case
when sex = 'female' and trending = 1 then 1
when sex = 'female' and trending = 0 then 2
when sex = 'male' and trending = 1 then 3
when sex = 'male' and trending = 0 then 4
end
返回ASC排序,因此最早的用户将首先显示。
当我尝试对大小写进行DESC排序时(如波纹管),它什么都不会改变:
when sex = 'female' and trending = 1 then 1
答案 0 :(得分:2)
根据您的要求,您需要按sex
升序排列(因此,女性是第一位),trending
降序排列(因此,趋势用户是第一位)和date_registered
降序排列(因此最近的用户是第一位)
select
id,
sex,
trending,
date_registered
from users
order by sex, trending desc, date_registered desc
您的小提琴的输出:
id sex trending date_registered
4 female 1 26-04-2020
5 female 1 25-04-2020
6 female 0 24-04-2020
7 female 0 23-04-2020
1 male 1 29-04-2020
2 male 1 28-04-2020
8 male 1 22-04-2020
3 male 0 27-04-2020
9 male 0 21-04-2020
答案 1 :(得分:0)
答案 2 :(得分:0)
仅在CASE块之后放置DESC(在END关键字之后):
select
id,
sex,
trending,
date_registered
from users
order by
case
when sex = 'female' and trending = 1 then 1
when sex = 'female' and trending = 0 then 2
when sex = 'male' and trending = 1 then 3
when sex = 'male' and trending = 0 then 4
end DESC