iteye_8786 2012-10-23 15:59
浏览 191
已采纳

怎样只用一条Select语句实现该规则下的排序?

我现在要写一条查询的SQL语句,试了很长时间还是没写出来,现求各位帮忙了~

 

假设有如下表格t_context,其中type共有A、B、C种类型,优先级依次为B>A>C,现在要查询该表格中的所有数据,不过须按如下规则排序:

1、类型为B的排在第一,若有多条则按时间递减;

2、类型为A的排在第二,若有多条则按时间递减;

3、剩下的则按时间递减即可。

 

 

id type date context
1 C xxxx-xx-xx xx:xx:xx ...
2 C xxxx-xx-xx xx:xx:xx ...
3 A xxxx-xx-xx xx:xx:xx ...
4 C xxxx-xx-xx xx:xx:xx ...
5 B xxxx-xx-xx xx:xx:xx ...
6

A

xxxx-xx-xx xx:xx:xx ...

 

 

 

 

 

 

 

 

 

 

 

怎样用一条select语句实现这种规则的排序结果?

  • 写回答

3条回答 默认 最新

  • iteye_7115 2012-10-23 16:26
    关注

    mysql实现:
    [code="sql"]select id,type,date,context from (
    select id,
    (case type when 'A' then 2 when 'B' then 3 else 1 end) level,
    type,
    date,
    context
    from t_context
    ) t
    order by t.level desc,t.date desc;[/code]

    oracle的话,可以把case部分用decode代替

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 怎么在stm32门禁成品上增加记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号