将多行数据合并为一行

时间:2013-11-06 05:15:57

标签: sql sql-server-2008

我有以下需要合并的数据:

+---------------------------------------------------------------------------------+
| eventid    username   loginstart          loginend            data1 data2 data3 |
+---------------------------------------------------------------------------------+
| 1234       abc        2013-11-04 02:22:22  2013-11-04 02:32:22   2     4     0  |
| 1239       abc        2013-11-04 02:22:22  2013-11-04 02:32:22   1     0     0  |
| 1232       cdf        2013-11-04 02:22:22  2013-11-04 02:32:22   2     4     0  |
+---------------------------------------------------------------------------------+

我需要的是输出如下所示:

+------------------------------------------------------------------------+
| username   loginstart           loginend             data1 data2 data3 |
+------------------------------------------------------------------------+
| abc        2013-11-04 02:22:22  2013-11-04 02:32:22   3     4     0    |
| cdf        2013-11-04 02:22:22  2013-11-04 02:32:22   2     4     0    |
+------------------------------------------------------------------------+

基本上,输出所做的是匹配该用户的loginstart和loginend内发生的事件,并将数据添加到一行。

欢迎任何提示,以达到所需的输出。

1 个答案:

答案 0 :(得分:2)

您需要使用汇总函数SUM(),然后使用GROUP BY

SELECT username, loginstart, loginend, SUM(data1) as TotData1, SUM(data2) as TotData2, SUM(data3) as TotData3
FROM YourTable
GROUP BY username, loginstart, loginend

示例链接here