我有一个与代理人的会话表,会话的开始时间以及他们帮助了多少人。我想查询每个代理/日期组合的总数,并结合当天的所有会话。例如,我有:
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将为所有选定的列返回唯一的结果,所以我只会看到原始数据,而不是按天组合。任何有关这方面的帮助将不胜感激,谢谢!
答案 0 :(得分:3)
这里你想要的是Agent
按SELECT CONVERT(CHAR(10), StartTime, 101) as 'Day',
Agent,
SUM(Helped) AS Helped
FROM Sessions
GROUP BY CONVERT(CHAR(10), StartTime, 101),
Agent
和日分组。
Day
我不记得SQL Server是否允许您在GROUP BY
中使用别名SELECT CONVERT(CHAR(10), StartTime, 101) as 'Day',
Agent,
SUM(Helped) AS Helped
FROM Sessions
GROUP BY Day, Agent,
。如果是,你可以做
{{1}}
答案 1 :(得分:2)
您需要GROUP BY
StartTime和代理以及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
答案 2 :(得分: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 |
答案 3 :(得分:-1)
我相信你会想要探索'group by'命令 - 就像这样:
SELECT CONVERT(CHAR(10), StartTime, 101) as 'Day',
Agent,
Helped
FROM Sessions GROUP BY (Agent) order by Agent asc