【问题标题】:Complex order by复杂的顺序
【发布时间】:2013-07-06 20:55:53
【问题描述】:

我在 mssql 查询中有一个 order by,需要以复杂的方式进行排序。我可以使用游标解决这个问题,但这不是最佳解决方案。

我的选择返回一个包含用户进入和退出、进入时间和退出时间的表,我需要对最早的条目进行排序,然后是他的退出,然后是第二个最早的条目,然后是那个人,等等。例如

日期----用户----操作(1是进入2是退出)

0622 ---- 4 --------- 1

0627 ---- 4 --------- 2

0623 ---- 1 --------- 1

0624 ---- 1 --------- 2

0624 ---- 3 --------- 1

0630 ---- 3 --------- 2

0701 ---- 4 --------- 1

0703 ---- 4 --------- 2

我想过在 order by 上使用 case where 但我不知道如何得到这个结果。

感谢您的帮助,

【问题讨论】:

  • 您当前的查询是什么?

标签: sql-server select sql-order-by case


【解决方案1】:

这是我的解决方案:

select
    your_table.[date],
    your_table.[user],
    your_table.[action]
from your_table
order by
    (case when your_table.[action]=1 then your_table.[date] else (select max(t.[date]) from your_table t where t.[action]=1 and t.[user]=your_table.[user] and t.[date]<=your_table.[date]) end),
    your_table.[user],
    your_table.[action];

【讨论】:

  • 抱歉没早点回复,我得看看你的解决方案,我会尽快做的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-28
  • 2019-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多