按日期统计
表格如下:
date num
07-1 2
07-1 3
07-1 4
07-1 5
07-1 2
07-2 1
07-2 22
07-2 12
07-2 11
07-3 66
... ...
想得到如下结果集
date 总数 最小值 数目 最大值 数目
07-1 5 2 2 5 1
07-2 3 11 1 22 1
.. .. .. .. .. ..
数目指最大/小值的个数。
------解决方案--------------------select date,count(*) as 总数,min(num) as 最小值,
数目=(select count(*) from tablename where
num=min(num) group by date) ,max(num) as 最大值,
数目=(select count(*) from tablename where
num=max(num) group by date) from tablename group by date
------解决方案--------------------create table T([date] varchar(10), num int)
insert T select '07-1 ', 2
union all select '07-1 ', 3
union all select '07-1 ', 4
union all select '07-1 ', 5
union all select '07-1 ', 2
union all select '07-2 ', 1
union all select '07-2 ', 22
union all select '07-2 ', 12
union all select '07-2 ', 11
union all select '07-3 ', 66
select [date], 总数=count(*),
最小值=min(num), 数目=(select count(*) from T where [date]=A.[date] and num=min(A.num)),
最大值=max(num), 数目=(select count(*) from T where [date]=A.[date] and num=max(A.num))
from T as A
group by [date]
--result
date 总数 最小值 数目 最大值 数目
---------- ----------- ----------- ----------- ----------- -----------
07-1 5 2 2 5 1
07-2 4 1 1 22 1
07-3 1 66 1 66 1
(3 row(s) affected)