我正在寻找计算某些数据的最佳方法。
我有一张如下表所示的表格:
|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 |
任何想法?
答案 0 :(得分: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