使用order by时的group with issue

时间:2014-02-19 10:17:41

标签: sql sql-server sql-server-2008

当我尝试分组但使用按语句排序时,我遇到了困难。

这是我的查询

create table AllData(NoOfPerson int,NoOfMinutes int,StartTime Datetime);

INSERT INTO AllData VALUES(1,2,GETDATE()),
(0,3,GETDATE()+1),
(3,4,GETDATE()+2),
(2,5,GETDATE()+3),
(0,6,GETDATE()+4),
(3,7,GETDATE()+5),
(2,8,GETDATE()+6);

和查询输出

select NoOfperson,SUM(NoOfMinutes)NoOfMinutes,MIN(StartTime)StartTime from AllData
group by NoOfperson,StartTime
order by StartTime

NoOfperson  NoOfMinutes StartTime
1               2   2014-02-19 15:44:52.617
0               3   2014-02-20 15:44:52.617
3               4   2014-02-21 15:44:52.617
2               5   2014-02-22 15:44:52.617
0               6   2014-02-23 15:44:52.617
3               7   2014-02-24 15:44:52.617
2               8   2014-02-25 15:44:52.617

但我希望输出应该像

首先

1  -- 2
0  -- 9
3  -- 11
2  -- 13

我如何获得此输出?

4 个答案:

答案 0 :(得分:3)

尝试换行查询:

SELECT * 
FROM   (SELECT noofperson, 
               Sum(noofminutes) NoOfMinutes, 
               Min(starttime)   StartTime 
        FROM   alldata 
        GROUP  BY noofperson) t 
ORDER  BY noofminutes ASC; 

或简单地说:

SELECT noofperson, 
       Sum(noofminutes) NoOfMinutes, 
       Min(starttime)   StartTime 
FROM   alldata 
GROUP  BY noofperson 
ORDER  BY noofminutes ASC; 

答案 1 :(得分:0)

试试这个:

SELECT NoOfperson, NoOfMinutes FROM
(
select NoOfperson,SUM(NoOfMinutes)NoOfMinutes,MIN(StartTime)StartTime from AllData
group by NoOfperson
) AS Data
GROUP BY NoOfperson, NoOfMinutes, StartTime
order by StartTime

答案 2 :(得分:0)

SELECT NoOfperson, SUM(NoOfMinutes) AS SumNoOfMinutes , MIN(StartTime)StartTime
from AllData
group by NoOfperson
order by SumNoOfMinutes asc ;

答案 3 :(得分:0)

怎么样,

select * , 
sum(NoOfMinutes)over(partition by NoOfPerson,NoOfPerson order by  NoOfPerson) 
from @AllData