2014-10-07 71 views
-1

我正在尋找計算某些數據的最佳方法。如何計算數據

我有一個表,如下圖所示:

|User| Operation | Date | Hint | 
--------------------------------------- 
|us1 | Add |2014-06-25|some text| 
|us1 | Add |2014-07-01|some text| 
|us1 | Delete |2014-07-12|some text| 
|us1 | Modify |2014-07-14|some text| 
|us1 | Update |2014-07-15|some text| 
|us2 | Add |2014-07-17|some text| 
|us2 | Add |2014-07-01|some text| 
|us2 | Modify |2014-07-14|some text| 
|us2 | Delete |2014-07-14|some text| 
|us2 | Update |2014-07-14|some text| 
|us2 | Update |2014-07-14|some text| 
|us2 | Update |2014-07-14|some text| 
|us2 | Update |2014-07-14|some text| 
|us2 | Update |2014-07-14|some text| 

我想寫一個SQL查詢來獲取一個表像下面:

|User|Add|Modify|Update|Delete| 
------------------------------- 
|us1 | 2 | 1 | 1 | 0 | 
|us2 | 2 | 1 | 5 | 1 | 

什麼想法?

回答

1

這就是你要找的。它使用條件計算。

SELECT 
[User], 
[Add] = SUM(CASE [Operation] WHEN 'Add' THEN 1 ELSE 0 END), 
[Modify] = SUM(CASE [Operation] WHEN 'Modify' THEN 1 ELSE 0 END), 
[Update] = SUM(CASE [Operation] WHEN 'Update' THEN 1 ELSE 0 END), 
[Delete] = SUM(CASE [Operation] WHEN 'Delete' THEN 1 ELSE 0 END) 
FROM [tablename] 
GROUP BY [User] 
ORDER BY [User] ASC