SQL 按时间戳排序并分配数值

SQL Order by Timestamp and Assign Numeric Value

我有一个 cust_id 列表和一个 activity 的时间戳。我想添加一个名为 "activity_order" 的列,它会向每个 cust_id 发出命令,其中“1”被分配给最大时间戳

 cust_id | time_stamp
 ________  __________
 a1        2015-01-31 10:48:43
 a1        2015-01-31 12:48:46
 a1        2015-01-31 17:50:40
 b1        2015-01-25 10:39:01
 b1        2015-01-31 12:53:34

这就是我想要的结果:

 cust_id | time_stamp            | activity_order
 ________  ___________________    _________________
 a1        2015-01-31 10:48:43     3    
 a1        2015-01-31 12:48:46     2
 a1        2015-01-31 17:50:40     1
 b1        2015-01-25 10:39:01     2
 b1        2015-01-31 12:53:34     1

这是我的尝试,但问题是这个 CASE 语句只有这么大,我想我需要一个循环或类似的东西,以防 cust_id 大于 > 2活动。

SELECT a.cust_id
,a.time_stamp
,CASE WHEN a.time_stamp = b.max_ts THEN 1 ELSE 2 END as activity_order
FROM ACTIVITY a
JOIN (SELECT
cust_id
,MAX(time_stamp) as max_ts
FROM activity_order) b
ON a.cust_id = b.cust_id
SELECT cust_id
, time_stamp
, RANK () OVER(PARTITION BY cust_id ORDER BY time_stamp DESC) as activity_order
FROM activity
ORDER BY cust_id ASC, activity_order DESC

工作示例:http://sqlfiddle.com/#!6/b6d85/3

更多信息:http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions123.htm

尝试假设 MS SQL

Update B
Set Activity_Order = RN
From
(select CustID, [Time_stamp], Row_Number() Over(Partition By CustID Order By [Time_stamp] desc) as RN
From Activity) A
inner join Activity B on A.CustID = B.CustID and A.[Time_stamp] = B.[Timestamp]

我希望我们 Row_Number 有一个分区。 注意:您使用 3 cust_ID :a1、b1、b2。但是您的示例在 b2 下订购了 b1。 这是您的示例中的错误吗?

这是我的尝试:

SELECT 
cust_id, time_stamp, 
activity_order = ROW_NUMBER() OVER (PARTITION BY cust_id ORDER BY cust_id     ASC, time_stamp DESC) 
FROM ACTIVITY