3

我有一个与代理的会话表、会话的开始时间以及他们帮助了多少人。我想查询查看每个代理/日期组合的总数,结合当天的所有会话。例如,我有:

Agent 1 - 1/8/13 11:30am - 8
Agent 2 - 1/8/13 11:32am - 9
Agent 1 - 1/8/13 12:45pm - 10
Agent 2 - 1/9/13 10:20am - 8
Agent 3 - 1/9/13 11:45am - 7

我想看到的是:

1/8/13 - Agent 1 - 18
1/8/13 - Agent 2 - 9
1/9/13 - Agent 2 - 8
1/9/13 - Agent 3 - 7

我尝试的是:

SELECT DISTINCT CONVERT(CHAR(10), StartTime, 101) as 'Day',
       Agent,
       Helped
FROM Sessions

但我现在明白 DISTINCT 将为所有选定的列返回唯一结果,所以我只会看到原始数据,而不是按天组合。对此的任何帮助将不胜感激,谢谢!

4

4 回答 4

3

你在这里想要的是按天分组的聚合SUM()Agent

SELECT CONVERT(CHAR(10), StartTime, 101) as 'Day',
       Agent,
       SUM(Helped) AS Helped
FROM Sessions
GROUP BY CONVERT(CHAR(10), StartTime, 101),
         Agent

我不记得 SQL Server 是否允许您DayGROUP BY. 如果是这样,你可以做

SELECT CONVERT(CHAR(10), StartTime, 101) as 'Day',
       Agent,
       SUM(Helped) AS Helped
FROM Sessions
GROUP BY Day, Agent, 
于 2013-01-11T21:11:12.660 回答
2

您需要GROUP BYStartTime 和 Agent 以及SUM帮助:

declare @Sessions table
(
    StartTime datetime,
    Agent varchar(50),
    Helped int
)

insert into @Sessions (Agent, StartTime, Helped)
select 'Agent 1', '1/8/13 11:30am', 8
union select 'Agent 2', '1/8/13 11:32am', 9
union select 'Agent 1', '1/8/13 12:45pm', 10
union select 'Agent 2', '1/9/13 10:20am', 8
union select 'Agent 3', '1/9/13 11:45am', 7

select
    convert(varchar(10), StartTime, 101) as [Day],
    Agent,
    sum(Helped)
from
    @sessions
group by
    convert(varchar(10), StartTime, 101),
    Agent
于 2013-01-11T21:15:30.267 回答
0

我想知道它是否太简单了......但似乎是你需要的答案..

询问:

SELECT date as times,
       id,
       sum(items)
FROM agents
group by id, date
;

结果:

|      TIMES |      ID | COLUMN_2 |
-----------------------------------
| 2013-01-08 | Agent 1 |       18 |
| 2013-01-08 | Agent 2 |        9 |
| 2013-01-09 | Agent 2 |        8 |
| 2013-01-09 | Agent 3 |        7 |
于 2013-01-11T21:20:28.430 回答
-1

我相信您会想要探索“分组依据”命令 - 如下所示:

SELECT CONVERT(CHAR(10), StartTime, 101) as 'Day',
   Agent,
   Helped
FROM Sessions GROUP BY (Agent) order by Agent asc
于 2013-01-11T21:11:40.027 回答