2012-12-25 140 views
0

當我運行這個(SQL Server 2008 R2中):分組/聚合在SQL Server 2008 R2

SELECT [UserId] 
     ,[StateDuration] 
     ,[StatusKey] 
FROM [AgentActivityLog] 
WHERE [StatusDateTime] between '2012-01-01' and '2012-12-31' 

我得到每個用戶ID一排這樣的: 用戶ID StatusDateTime StatusKey

cfrinco  3456 Meeting 
echartl  23456 Available 
mbarbewar 3256 Lunch 
bsantiago 46565 Available 
bsantiago 79  Follow Up 
fburger  5464 Available 

哪告訴我幾秒鐘內每個用戶處於每種狀態的時間。

當然,每個日期每UserId會有很多條目。 換句話說,用戶,在一天內,從可用到會議爲可用以午飯可用等

我想要做的總時間(秒)每UserId,每StatusKey是,每個日曆日。所以它看起來像這樣:

cfrinco  3456 Meeting  '2012-01-01' 
cfrinco  45678 Available  '2012-01-01' 
cfrinco  7845 Meeting  '2012-01-02' 
cfrinco  32541 Available  '2012-01-02' 
cfrinco  4455 Meeting  '2012-01-03' 
cfrinco  12456 Available  '2012-01-03' 
fburger  3456 Meeting  '2012-01-01' 
fburger  75489 Available  '2012-01-01' 
fburger  3541 Lunch   '2012-01-01' 
fburger  5486 Meeting  '2012-01-02' 
fburger  64587 Available  '2012-01-02' 
fburger  3614 Lunch   '2012-01-02' 
fburger  3225 Meeting  '2012-01-03' 
fburger  35414 Available  '2012-01-03' 
fburger  3745 Lunch   '2012-01-03' 

您的幫助是非常感謝。

回答

0

這就是我一直在尋找。在對stackoverflow中的不同答案進行了一些研究並將它們放在一起之後,我得到了它。

SELECT 
UserId, SUM(StateDuration) SumStateDuration, StatusKey, 
DATEADD(dd, 0, DATEDIFF(dd, 0, StatusDateTime)) StatusDate 
FROM [AgentActivityLog] 
WHERE StatusDateTime BETWEEN '2012-01-01' AND '2012-12-31' 

GROUP BY 
UserId, 
DATEADD(dd, 0, DATEDIFF(dd, 0, StatusDateTime)), 
StatusKey 

的關鍵部分是 (a)以得到公正的日期出datetime列和(b)組。

1

如果要通過用戶ID,狀態和日期分組數據,然後做一些事情,如:

SELECT 
UserId 
SUM(StateDuration), 
StatusKey, 
StatusDateTime 
FROM AgentActivityLog 
WHERE StatusDateTime BETWEEN '2012-01-01' AND '2012-12-31' 
GROUP BY 
UserId, 
StatusDateTime, 
StatusKey 
+0

對不起,我不清楚。每個日期每個'UserId'都會有很多條目。換句話說,一天中的用戶將從可用到會議到可用到午餐到可用等。謝謝! – Amarundo