0

我有下表

UNIQUEKEY    ID      Clicks IsProcessed   INSERTDATE
 1         100001   10        1         2011-05-14 00:00:00.000
 2         100001   20        0         2011-05-13 00:00:00.000
 3         100001   30        1         2011-05-18 00:00:00.000
 4         100002   10        1         2011-05-20 00:00:00.000
 5         100002   15        0         2011-05-24 00:00:00.000
 6         100002   10        0         2011-05-05 00:00:00.000

我需要一个 T-SQL 查询,该查询将首先按 INSERTDATE (desc) 排序,一旦订购,它应该返回一个 GROUP by on ID 和 IsProcessed,结果应该显示所有列 Orderby 并按如上所述分组。

编辑:所以如果我们运行查询让我们说它ID 10001应该给我 2 个结果集: 期望的结果:

UNIQUEKEY    ID      Clicks IsProcessed   INSERTDATE
 3         100001   30        1         2011-05-18 00:00:00.000
 1         100001   10        1         2011-05-14 00:00:00.000        
 2         100001   20        0         2011-05-13 00:00:00.000

Reson 正在IDIsProcessed用作键,结果按 排序Date (desc)

任何帮助,将不胜感激 !

4

1 回答 1

3

尝试这个:

declare @ID int = 100001
declare @IsProcessed int

declare
  crsMy cursor fast_forward for
select
  distinct IsProcessed
from
  tTest
order by
  IsProcessed desc

open crsMy

fetch next from crsMy into @IsProcessed

while @@fetch_status = 0
begin
  select
    UNIQUEKEY
    ,ID
    ,Clicks
    ,IsProcessed
    ,INSERTDATE
  from
    tTest
  where
    (ID=@ID)
    and
    (IsProcessed=@IsProcessed)
  order by
    INSERTDATE desc



  fetch next from crsMy into @IsProcessed
end

close crsMy
deallocate crsMy

或在sql fiddle

(在 sqlfiddle 上仅显示第一个结果集。)

于 2012-10-04T06:47:15.460 回答