T-SQL GROUP BY

前段时间,有举过一些函数例子,如SUM,COUNT,MAX,MIN,AVG,当我们调用这些函数进行运算,再想对这些运算结果进行分组,那得需使用GROUP BY来实现。

下面先准备一些数据。创建一个表[RecordHits],并填充一些数据:

View Code
CREATE TABLE RecordHits 
(
    RId 
NVARCHAR(2),
    DT DATE,
    Hits 
INT
)
GO

INSERT INTO [dbo].[RecordHits] VALUES
(
'R1','2011-01-23',30),
(
'R2','2011-01-23',33),
(
'R3','2011-01-23',29),
(
'R4','2011-01-23',31),
(
'R1','2011-01-24',25),
(
'R2','2011-01-24',35),
(
'R3','2011-01-24',43),
(
'R4','2011-01-24',37),
(
'R1','2011-01-25',24),
(
'R2','2011-01-25',40),
(
'R3','2011-01-25',36),
(
'R4','2011-01-25',42),
(
'R1','2011-01-26',36),
(
'R2','2011-01-26',42),
(
'R3','2011-01-26',27),
(
'R4','2011-01-26',33)
GO

 

下面例子,是对查询出每笔记点击数和进行分组:

SELECT [RId],SUM([Hits]AS [TotalHits] FROM [dbo].[RecordHits]
GROUP BY [RId]

 

结果:

 

posted @ 2011-03-01 16:56  Insus.NET  阅读(868)  评论(0编辑  收藏  举报