在SQL Server 2012+你可以使用common table expression與lag()
檢查,然後case
表達的min()
後面,像這樣你的邏輯:
;with cte as (
select *
, prev_activity = lag(activity) over (partition by id order by date_of_activity)
from t
)
select id
, right_order = min(case
when activity = 'a' and isnull(prev_activity,'b')<>'b' then 'no'
when activity = 'b' and isnull(prev_activity,'b')<>'a' then 'no'
else 'yes'
end)
from cte
group by id
rextester演示:http://rextester.com/NQQF78056
回報:
+----+-------------+
| id | right_order |
+----+-------------+
| 1 | yes |
| 2 | no |
+----+-------------+
之前的SQL Server 2012中您可以使用outer apply()
獲得以前的活動,而不是lag()
像這樣:
select id
, right_order = min(case
when activity = 'a' and isnull(prev_activity,'b')<>'b' then 'no'
when activity = 'b' and isnull(prev_activity,'b')<>'a' then 'no'
else 'yes'
end)
from t
outer apply (
select top 1 prev_activity = i.activity
from t as i
where i.id = t.id
and i.date_of_activity < t.date_of_activity
order by i.date_of_activity desc
) x
group by id
我不清楚你問什麼? – ssn
請澄清你的問題。這有點混亂。向我們展示一個輸出示例。 –
從您發佈的數據來看,這是不可能的。根據定義,表格是一個無序集合,你沒有任何東西可以提供一致的順序。 –