数据库分组统计得到如下结果 名称 号码 A 001 A 002 A 003 A 005 A 007 A 009 A 010 B 012需得到结果为 A 001-003,005,007,009-010 B 012
呵呵献丑了 int[] Temp = new int[] { 1, 2, 3, 5, 7, 9, 10 }; List<int[]> DesT = new List<int[]>(); List<int> DesI = new List<int>(); foreach (int TI in Temp) { if (DesI.Count != 0 && TI - 1 != DesI[DesI.Count - 1]) { DesT.Add(DesI.ToArray()); DesI.Clear(); } DesI.Add(TI); } DesT.Add(DesI.ToArray()); DesI.Clear();
declare @t table(num int) insert into @t select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 12 union all select 17 union all select 18 union all select 19 union all select 20 union all select 25 select rtrim(a.num)+(case when min(b.num)!=a.num then '-'+rtrim(min(b.num)) else '' end) from (select t.num from @t t where not exists(select 1 from @t where num=t.num-1)) a, (select t.num from @t t where not exists(select 1 from @t where num=t.num+1)) b where a.num<=b.num group by a.num------------------------- 1-5 12 17-20 25 */
参考我问过的,各种情况和做法都有了
名称 号码
A 001
A 002
A 003
A 005
A 007
A 009
A 010
B 012需得到结果为
A 001-003,005,007,009-010
B 012
List<int[]> DesT = new List<int[]>();
List<int> DesI = new List<int>();
foreach (int TI in Temp)
{
if (DesI.Count != 0 && TI - 1 != DesI[DesI.Count - 1])
{
DesT.Add(DesI.ToArray());
DesI.Clear();
}
DesI.Add(TI);
}
DesT.Add(DesI.ToArray());
DesI.Clear();
insert into @t select 1
union all select 2
union all select 3
union all select 4
union all select 5
union all select 12
union all select 17
union all select 18
union all select 19
union all select 20
union all select 25 select
rtrim(a.num)+(case when min(b.num)!=a.num then '-'+rtrim(min(b.num)) else '' end)
from
(select t.num from @t t where not exists(select 1 from @t where num=t.num-1)) a,
(select t.num from @t t where not exists(select 1 from @t where num=t.num+1)) b
where
a.num<=b.num
group by a.num-------------------------
1-5
12
17-20
25
*/