如何按照时间段进行分组汇总数据查询,例如以下表结构name  score  datetimetom     34   2009-1-3 13:52:11
cake    22   2009-1-7 16:13:11
pitty   67   2009-4-3 08:22:42
jerry   52   2009-4-21 08:22:42
ket     52   2009-9-15 10:11:42
......................
......................
......................我想达到以下目的,就是按照每个月来返回 score字段的汇总,用sql语句能达到这个目的吗?

解决方案 »

  1.   

    select
     convert(varchar(7),datetime,120), sum(score) 
    from 
     tb 
    group by 
     convert(varchar(7),datetime,120),
      

  2.   

    ---多了个,号
    ----------------------------------------------------------------
    -- Author  :fredrickhu(我是小F,向高手学习)
    -- Date    :2009-12-02 09:21:17
    -- Version:
    --      Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86) 
    -- Nov 24 2008 13:01:59 
    -- Copyright (c) 1988-2005 Microsoft Corporation
    -- Developer Edition on Windows NT 5.2 (Build 3790: Service Pack 1)
    --
    ----------------------------------------------------------------
    --> 测试数据:[tb]
    if object_id('[tb]') is not null drop table [tb]
    go 
    create table [tb]([name] varchar(5),[score] int,[datetime] datetime)
    insert [tb]
    select 'tom',34,'2009-1-3 13:52:11' union all
    select 'cake',22,'2009-1-7 16:13:11' union all
    select 'pitty',67,'2009-4-3 08:22:42' union all
    select 'jerry',52,'2009-4-21 08:22:42' union all
    select 'ket',52,'2009-9-15 10:11:42'
    --------------开始查询--------------------------
    select
     convert(varchar(7),datetime,120), sum(score) 
    from 
     tb 
    group by 
     convert(varchar(7),datetime,120)
    ----------------结果----------------------------
    /* ------- -----------
    2009-01 56
    2009-04 119
    2009-09 52(3 行受影响)*/
      

  3.   

    --呵呵:小F多了个逗号
    select
     convert(varchar(7),datetime,120), sum(score) 
    from 
     tb 
    group by 
     convert(varchar(7),datetime,120);
      

  4.   

    name  score  datetime 
    if object_id [TB] DROP table [TB]
    create table [TB](name varchar(20),score int,datetime datetime)
    insert [TB] select     'tom',   '34', '2009-1-3 13:52:11'
               union all   'cake' , '22',  '2009-1-7 16:13:11' 
               union all   'pitty', '67',  '2009-4-3 08:22:42' 
               union all   'jerry', '52',  '2009-4-21 08:22:42' 
               union all   'ket' ,  '52',  '2009-9-15 10:11:42' 
    select name,sum(score),datetime from [TB]  group by convert(datetime,datetime,120)