需要求和查询的结果

时间:2013-04-11 10:25:14

标签: sql sql-server sql-server-2008

查询Q返回两列 - DateOfWorkdatetimeCallsTakenOnDateint

也就是说,我们获得特定电话交换机在指定日期所接听的电话数量。

如何创建一个函数,该函数将在n天内返回特定电话交换的CallsTakenOnDate列的总和?

表格结构 -

DateOfWork  | CallsTakenOnDate
-------------------------------
2013-10-5   | 200
2013-10-6   | 100
2013-10-7   | 700        

我想总结CallsTakenOnDate

2 个答案:

答案 0 :(得分:3)

试试这个 -

CREATE FUNCTION dbo.udf_getCountCallOnDate
(
      @DateFrom DATETIME
    , @DateTo DATETIME
)
RETURNS INT
AS
BEGIN

    RETURN (
        SELECT SUM(CallsTakenOnDate) 
        FROM dbo.PhoneCalls
        WHERE DateOfWork BETWEEN @DateFrom AND @DateTo
    )

END

SELECT 
  DateOfWork = CONVERT(VARCHAR(10), t.DateOfWork, 111)
, [Count] = SUM(t.CallsTakenOnDate) 
FROM dbo.PhoneCalls t
WHERE DateOfWork BETWEEN @DateFrom AND @DateTo
ORDER BY t.DateOfWork

答案 1 :(得分:0)

我今天遇到了同样的问题:

select
  sum(CallsTakenOnDate) as count,
  DATE_FORMAT(DateOfWork, "%Y-%m-%d %H:00:00") AS date
from
  raw_visits
group by hour(DateOfWork),day(DateOfWork),month(DateOfWork),year(DateOfWork);

每天这个群组,但您可以通过群组声明进行调整。