使用SQL语句汇总数据

时间:2010-05-26 15:44:47

标签: sql mysql

我的CMS表包含CMS_STARTTIME和CMS_STOPTIME(附件)。
alt text http://img339.imageshack.us/img339/755/exdatabase.jpg

我想创建报告,通过使用日期,时间和年份作为参数(附件)来汇总现有数据。
alt text http://img444.imageshack.us/img444/3508/reportdailyen.jpg

我不知道如何创建sql语句来满足这个要求。我正在使用MySQL和MS-SQL。 有人可以帮忙吗?
非常感谢你。

2 个答案:

答案 0 :(得分:3)

这是SQL Server的解决方案

SELECT 
 DATEPART(hh,CMS_StartTime)  AS HourOfDay, 
 COUNT(*)              AS NumMsgs, 
 SUM(DATEDIFF(mi,CMS_StartTime,CMS_STOPTIME)) AS TotalTimeInMinutes,
 AVG(DATEDIFF(mi,CMS_StartTime,CMS_STOPTIME)) AS AvgTimeBetweenInMinutes
FROM 
      MyTable   
WHERE CMS_StartTime
      BETWEEN 'may 1 2010' AND 'may 2 2010'
GROUP BY
      DATEPART(hh,CMS_StartTime)

答案 1 :(得分:2)

要使其工作,您需要一个Numbers或Tally表,其中包含从零开始的整数顺序列表。在我的示例中,我的Numbers表看起来像:

Create Table Numbers ( Value int not null primary key )

使用它并在SQL Server中执行此操作,您可以执行以下操作:

Select N.Value As [Hour]
    , Count(T.StartDate) As CallCount
    , Sum(DateDiff(mi, T.StartDate, T.EndDate)) As [TotalTime(mi)]
    , Avg(DateDiff(mi, T.StartDate, T.EndDate)) As [AvgTime(mi)]
From Numbers As N
    Left Join Table As T
        On DatePart(hh, T.StartDate) = N.Value
Where N.Value Between 0 And 23  
Group By N.Value

由于你没有指定,我假设一个呼叫在给定的小时内计数,如果它在那个小时开始。一个参数可能会使一个小时内的呼叫计算在一个小时内开始或结束,这会产生重复计算,但会告诉您在一天中的给定时间内正在进行的呼叫数量。为此,需要更改上面的查询以将以下内容添加到On子句Or DatePart(hh, T.EndDate) = N.Value

我相信MySql的等价物是:

Select N.Value As [Hour]
    , Count(T.StartDate) As CallCount
    , Sum( TimestampDiff(MINUTE, T.StartDate, T.EndDate) ) As [TotalTime(mi)]
    , Avg( TimestampDiff(MINUTE, T.StartDate, T.EndDate) ) As [AvgTime(mi)]
From Numbers As N
    Left Join Table As T
        On Hour(T.StartDate) = N.Value
Where N.Value >= 0 And N.Value <= 23    
Group By N.Value