sql date range in column and count by group

最后都变了- 提交于 2020-01-06 03:55:06

问题


I am trying to get a report where you can select a date range and get some counts. My table is something like this

--------------------------------------
RecID|AgentID|date
--------------------------------------
1    |00123  | 05/09/2012 16:28:49
2    |00123  | 05/09/2012 17:28:49
3    |00124  | 05/09/2012 18:28:49
4    |00124  | 06/09/2012 19:28:49
5    |00125  | 06/09/2012 20:28:49

I want something like

--------------------------------------
AgentID|05/09/2012|06/09/2012
--------------------------------------
00123  | 2        | 0
00124  | 1        | 1
00125  | 0        | 1

The code I have is

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX),
    @INIDate as date,
    @ENDDate as date,
    @INIDateVAR nvarchar(50),
    @ENDDateVAR nvarchar(50)

Set @INIDate = '10-01-2014'
Set @ENDDate = '10-10-2014'


DECLARE @sql NVARCHAR(MAX) = N'SELECT agentID';

;WITH dr AS
(

  SELECT MinDate = @INIDate,
         MaxDate = @ENDDate
),
n AS
(
  SELECT TOP (DATEDIFF(DAY, (SELECT MinDate FROM dr), (SELECT MaxDate FROM dr)) + 1)
   d = DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY [object_id])-1, 
     (SELECT MinDate FROM dr))
 FROM sys.all_objects
)
SELECT @sql += ',
  (Select Count(*) From AllRecordsView) as ' + QUOTENAME(d) 
   FROM n;

SELECT @sql += ' FROM dbo.AllRecordsView Group by AgentID;'

EXEC sp_executesql @sql;
GO

But this gets very slow when I select a big date range and the results I get are of course the count of the complete table.

Any ideas? Thanks


回答1:


You can use the day() function (depends on the database) to extract the day from the date field and use it in the GROUP BY. For the range use SQL BETWEEN.

If you still have performance issues, you should create an index on the AgentID and the date column.

SELECT dateColumn, AgentID, count(AgentID) AS agentCount
FROM YourTable
WHERE dateColumn BETWEEN '2012-09-05' AND '2012-09-09'
GROUP BY day(dateColumn), AgentID
ORDER BY dateColumn;




回答2:


What I end up doing is using Reporting Services. That way I can assign all the values from a column as a columns, one per each row.



来源:https://stackoverflow.com/questions/21430190/sql-date-range-in-column-and-count-by-group

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!