按半小时插槽分组不起作用

时间:2013-11-08 08:49:42

标签: sql sql-server grouping

this question's answer and comments之后,我试图让我的半小时插槽分组工作,但无论出于何种原因,它不会将行编号分别为1或2,具体取决于分钟是否为大于或小于30。

任何人都可以给我一些关于我出错的地方的线索吗?

select Deal, Price
from (select md.*,
            row_number() over (partition by case when (datepart(minute, Deal) < 30) then 1 else 2 end
                               order by Deal desc) as seqnum
      from MyData md
      where Product = 'XXXXX' AND
            CAST(Deal AS Date) = '2013-09-04'
     ) md
where seqnum = 1;

seqnum列实际上从1变为N,而不是在Deal字段中低于或超过30分钟时为1,2。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

这是因为SeqNum在该查询中并不是1或2。序列号是基于该1或2值对数据进行分区时的行号。这意味着每分钟的值都小于1分钟。 30被分成一组,然后按交易订购,它们从1到N编号。然后对于Deal&gt; = 30也是如此。

要做你想做的事情,你应该按日期,小时以及你的1或2值进行分区,然后将每个半小时的记录分成几组并编号,这样SeqNum =每半小时第一次记录为1。

尝试将您的seqnum更改为:

row_number() over (partition by 
              CAST(Deal AS DATE)
            , DATEPART(HOUR, Deal)
            , case when (datepart(minute, Deal) < 30) then 1 else 2 end
                               order by Deal ASC) 
            as seqnum

此处仅分为如此多的行以便于阅读。

要显示正在执行的序列号,请尝试运行:

select md.*
    ,CAST(Deal AS DATE) AS [Date]
    ,DATEPART(HOUR, Deal) AS [Hour]
    ,case when (datepart(minute, Deal) < 30) then 1 else 2 END AS [WhichHalf]
    ,row_number() over (partition by 
              CAST(Deal AS DATE)
            , DATEPART(HOUR, Deal)
            , case when (datepart(minute, Deal) < 30) then 1 else 2 end
                               order by Deal ASC) 
            as seqnum
from MyData md
where Product = 'XXXXX' AND
    CAST(Deal AS Date) = '2013-09-04'
ORDER BY Deal

希望你有足够的数据可以明白序列号在那里做什么。 (带有交易= 12:01的记录可能会被编号为SeqNum = 1,那么之后的每条记录将被编号为2,3,4 ......直到它超过12:30,此时它将再次重置为1)< / p>