详细查询按月拆分的查询

时间:2014-03-19 14:53:30

标签: sql-server

我有以下MS SQL查询:

SELECT DNIS, COUNT(*) AS Numbers
  FROM I3_IC.dbo.CallDetail_Viw WITH (NOLOCK)
WHERE CallDirection = 'Inbound'
   AND CallType = 'External' 
   AND InteractionType = 0
GROUP BY DNIS
ORDER BY DNIS; 

返回如下列表:

DNIS           Count

+12013317062   34

+12018841142   1

+12019771912   1

+12025594026   72

这是2年的时间。我想每月分解

这是数据库的布局我从(某些字段省略)获取此数据

CallId
CallType
CallDirection
LineId
RemoteNumberFmt
RemoteNumberCallId
InitiatedDate
InitiatedDateTimeGmt
ConnectedDate
ConnectedDateTimeGmt
TerminatedDate
TerminatedDateTimeGmt
DNIS
CallEventLog

InitiatedDate和InitiatedDateTimeGmt字段是基于以下内容保存基于日期时间服务器的广告GMT的字段:2013-02-11 23:01:26.000

任何建议都适用。

2 个答案:

答案 0 :(得分:0)

按月分组。你的问题中有什么我想念的吗?

SELECT DNIS, YEAR(InitiatedDate) as [Year], MONTH(InitiatedDate) as [Month], COUNT(*) AS Numbers
  FROM I3_IC.dbo.CallDetail_Viw WITH (NOLOCK)
WHERE CallDirection = 'Inbound'
   AND CallType = 'External' 
   AND InteractionType = 0
GROUP BY DNIS, YEAR(InitiatedDate), MONTH(InitiatedDate)
ORDER BY DNIS, YEAR(InitiatedDate), MONTH(InitiatedDate); 

答案 1 :(得分:0)

您可以使用DATEPART功能从InitiatedDate字段中提取月份和年份,然后将这些值包含在GROUP BY中。您也可以在ORDER BY中使用这些功能。

SELECT DNIS, COUNT(*) AS Numbers, DATEPART(mm, InitiatedDate) AS Month, DATEPART(yyyy, InitiatedDate) AS Year
  FROM I3_IC.dbo.CallDetail_Viw WITH (NOLOCK)
WHERE CallDirection = 'Inbound'
   AND CallType = 'External' 
   AND InteractionType = 0
GROUP BY DNIS, DATEPART(yyyy, InitiatedDate), DATEPART(mm, InitiatedDate) 
ORDER BY DNIS, DATEPART(yyyy, InitiatedDate), DATEPART(mm, InitiatedDate) ;