我有一张如下表所示的表格,我需要按照ID和类型对每个约会和分组进行计数,然后按最早的约会排序并给它一个数字并计算。
我正在使用MS SQL服务器管理工作室。
Select ID, Date, Type
From Appointment
Where Type='Post-op'
在
ID | Date | Type
123 | 2013-01-01 | Post-op
123 | 2013-01-21 | Post-op
123 | 2013-02-28 | Post-op
123 | 2013-05-16 | Post-op
124 | 2013-01-21 | Post-op
124 | 2013-02-12 | Post-op
在
ID | Date | Type | Count
123 | 2013-01-01 | Post-op | 1
123 | 2013-01-21 | Post-op | 2
123 | 2013-02-28 | Post-op | 3
123 | 2013-05-16 | Post-op | 4
124 | 2013-01-21 | Post-op | 1
124 | 2013-02-12 | Post-op | 2
由于
答案 0 :(得分:2)
在SELECT
中使用窗口函数SELECT id
,[date]
,type
,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY [date] ) AS seq
FROM Appointment
WHERE Type = 'Post-op'
SqlFiddle:http://sqlfiddle.com/#!3/f3a4f/1
答案 1 :(得分:0)
似乎你在ROW_NUMBER
之后;with TempData as (Select ID ,Date,Type DataCount =ROW_NUMBER()
over(PARTITION By Id Order By Date)
From Appointment
Where Type='Post-op')
Select * from TempData