SQL Server:按范围分组日期

时间:2013-12-02 14:24:29

标签: sql sql-server stored-procedures group-by

我有一个SQL表,其中一列(dateRec)包含日期,格式为:yyyy-mm-dd。

在SQL中我是否可以定义日期范围,然后按这些范围对所有项目进行分组? 我在这里需要以下小组:

  • 第一组= 0 - 7天
  • 第二组= 8 - 14天
  • 第三组= 15 - 30天
  • 第四组= 31 - 60天
  • 第五组=休息

我从该表中获取所有项目的标准查询:

CREATE PROCEDURE [dbo].[FetchRequests]
AS
BEGIN
    SET NOCOUNT ON;
    SELECT      subject,
                dateRec,
                category
    FROM        LogRequests
    WHERE       logStatus = 'active'
    ORDER BY    dateRec desc, subject
    FOR XML PATH('items'), ELEMENTS, TYPE, ROOT('ranks')

END

感谢您对此提供任何帮助,Tim。

3 个答案:

答案 0 :(得分:15)

你需要做这样的事情

select t.range as [score range], count(*) as [number of occurences]
from (
  select case 
    when score between  0 and  9 then ' 0-9 '
    when score between 10 and 19 then '10-19'
    when score between 20 and 29 then '20-29'
    ...
    else '90-99' end as range
  from scores) t
group by t.range

点击此链接In SQL, how can you "group by" in ranges?

答案 1 :(得分:6)

是的,您可以通过添加一个新列来实现这一点,该列包含您需要的所有波段,然后按该列分组:

 SELECT      subject,
            dateRec,
            category
            ,case when datediff(day,dateRec,Getdate())<='7' then '0 - 7 days old'
                  when datediff(day,dateRec,Getdate()) between  '8' and '14' then '8 - 14 days old'
                   when datediff(day,dateRec,Getdate()) >60 then 'rest'
                   end Classes
       into #temp1
   FROM        LogRequests
   WHERE       logStatus = 'active'
   ORDER BY    dateRec desc, subject

我错过了你的几个范围,但希望你有逻辑

然后按此栏分组:

  select classes,
       Count(*)
      from #temp1

     begin drop table #temp1 end

答案 2 :(得分:2)

WITH ranges AS (
    SELECT
        range_id,
        ISNULL(DATEADD(day,range_start,CAST(GETDATE() AS date)),'0000-01-01') range_start,
        ISNULL(DATEADD(day,range_end  ,CAST(GETDATE() AS date)),'9999-12-31') range_end
    FROM (VALUES
        (1,  -7,  0),
        (2, -14, -8),
        (3, -30,-15),
        (4, -60,-31),
        (5,NULL,-61)
    ) r(range_id,range_start,range_end)
)
SELECT      subject,
            range_id,
            category
            COUNT(*) AS c,
FROM        LogRequests
WHERE       logStatus = 'active'
INNER JOIN  ranges ON dateRec BETWEEN range_start AND range_end
GROUP BY    subject,category,range_id
ORDER BY    range_id desc, subject