当前位置: 代码迷 >> Sql Server >> 求一条SQL语句记录数!
  详细解决方案

求一条SQL语句记录数!

热度:50   发布时间:2016-04-27 15:12:35.0
求一条SQL语句记录数!!!在线等~~~~~
有一表cxtbl,如下字段:
cxid           cxdh5
  9               A红蓝
  10             A红黑
  12             B青蓝
  13             C绿红
  14             D青红
  20             A黑黑
  21             C红红
  22             B蓝红

需要求出最高不出记录数:
A     最高有3次
B     最高有4次
C     最高有3次
D     最高有4次


------解决方案--------------------
求出最高不连续出现次数:

declare @test table(cxid int, cxdh5 varchar(30))
insert @test
select 9, 'A红蓝 '
union all
select 10, 'A红黑 '
union all
select 12, 'B青蓝 '
union all
select 13, 'C绿红 '
union all
select 14, 'D青红 '
union all
select 20, 'A黑黑 '
union all
select 21, 'C红红 '
union all
select 22, 'B蓝红 '

declare @cxid int, @cxdh5 varchar(30), @maxA int, @maxB int, @maxC int, @maxD int
declare @tmaxA int, @tmaxB int, @tmaxC int, @tmaxD int
set @maxA=0
set @maxB=0
set @maxC=0
set @maxD=0
set @tmaxA=0
set @tmaxB=0
set @tmaxC=0
set @tmaxD=0

declare cursor_test cursor for
select cxdh5
from @test
order by cxid

open cursor_test
fetch next from cursor_test into @cxdh5
while @@fetch_status=0
begin
if left(@cxdh5,1)= 'A '
begin
if @tmaxA> @maxA
set @[email protected]
set @tmaxA=0
end
else
begin
set @[email protected]+1
end

if left(@cxdh5,1)= 'B '
begin
if @tmaxB> @maxB
set @[email protected]
set @tmaxB=0
end
else
begin
set @[email protected]+1
end

if left(@cxdh5,1)= 'C '
begin
if @tmaxC> @maxC
set @[email protected]
set @tmaxC=0
end
else
begin
set @[email protected]+1
end

if left(@cxdh5,1)= 'D '
begin
if @tmaxD> @maxD
set @[email protected]
set @tmaxD=0
end
else
begin
set @[email protected]+1
end
fetch next from cursor_test into @cxdh5
end
close cursor_test
deallocate cursor_test

select 'A 最高有 '+cast(@maxA as varchar(5))+ '次 '
, 'B 最高有 '+cast(@maxB as varchar(5))+ '次 '
, 'C 最高有 '+cast(@maxC as varchar(5))+ '次 '
, 'D 最高有 '+cast(@maxD as varchar(5))+ '次 '


(所影响的行数为 8 行)


---------------- ---------------- ---------------- ----------------
A 最高有3次 B 最高有4次 C 最高有3次 D 最高有4次

(所影响的行数为 1 行)

------解决方案--------------------

create table test(cxid int, cxdh5 varchar(30))
insert test
select 9, 'A红蓝 '
union all
select 10, 'A红黑 '
union all
select 12, 'B青蓝 '
union all
select 13, 'C绿红 '
union all
select 14, 'D青红 '
union all
select 20, 'A黑黑 '
union all
select 21, 'C红红 '
union all
select 22, 'B蓝红 '
GO

select cxdh5, '最高有 '+rtrim(MAX(CNT))+ '次 ' FROM
  相关解决方案