日期:2014-05-18  浏览次数:20511 次

一条SQL还没完全解决,高手请进!!!~~~~~在线等~~~~
需要求出最高不出记录数:
A     最高有11次
B     最高有11次
D     最高有9次
E     最高有13次


create   table   test(cxid   int,   cxdh5   varchar(30))
insert   test
select   17, 'A红色 '
union   all
select   18, 'A蓝色 '
union   all
select   19, 'A绿色 '
union   all
select   20, 'D红色 '
union   all
select   21, 'L黄色 '
union   all
select   22, 'E蓝色 '
union   all
select   23, 'J蓝色 '
union   all
select   24, 'L蓝色 '
union   all
select   25, 'K红色 '
union   all
select   26, 'I黄色 '
union   all
select   27, 'G红色 '
union   all
select   28, 'B绿色 '
union   all
select   29, 'L红色 '
union   all
select   30, 'D黄色 '
union   all
select   31, 'A绿色 '
union   all
select   32, 'B绿色 '
union   all
select   33, 'H绿色 '
union   all
select   34, 'I绿色 '
union   all
select   35, 'F绿色 '
GO

select   cxdh5, '最高有 '+rtrim(MAX(CNT))+ '次 '   FROM  
(
        select   LEFT(B.cxdh5,1)   cxdh5,A.cxid   acxid,B.cxid   bcxid,
        (select   count(1)   from   test   where   cxid> ISNULL(A.cxid,0)   and   cxid <B.cxid)   CNT
          from   test   A   right   join   test   B  
        on   LEFT(B.cxdh5,1)=LEFT(A.cxdh5,1)  
        AND   A.cxid=(select   max(cxid)   from   test   where   LEFT(cxdh5,1)=LEFT(A.cxdh5,1)   AND   cxid <B.cxid   )
)   T   GROUP   BY   cxdh5

--为什么E的最高是5次,应该是有13次不出现E才对。
--             J的最高是6次,应该是有12次不出现E才对
--             K的最高是8次,应该是有10次不出现K才对。
--             L的最高是4次,应该是有6次不出现L才对。


------解决方案--------------------
上面错了!用下面一句:

select f1,max(f2) as 最高不出现次数 from
(
select left(A.cxdh5,1) as f1,count(*) as f2 from test A,test B
where left(A.cxdh5,1) <> left(B.cxdh5,1)
and A.cxid <B.cxid
and not exists(select 1 from test
where cxid> A.cxid and cxid <B.cxid and left(cxdh5,1)=left(A.cxdh5,1))
group by A.cxid,left(A.cxdh5,1)
) T
group by f1
order by f1

f1 最高不出现次数
---- -----------
A 11
B 3
D 9
E 13
G 8
H 2
I 7
J 12
K 10
L 6

(所影响的行数为 10 行)
------解决方案--------------------
--這樣算不算一條SQL麼?
select T.f1,max(case when T.f2> =T2.f2 then T.f2 else T2.f2 end) as 最高不出现次数 from
(
select left(A.cxdh5,1) as f1,count(*) as f2 from test A,test B
where left(A.cxdh5,1) <> left(B.cxdh5,1)
and A.cxid <B.cxid
and not exists(select 1 from test
where cxid> A.cxid and cxid <B.cxid and left(cxdh5,1)=left(A.cxdh5,1))
group by A.cxid,left(A.cxdh5,1)
) T
inner join (select left(A.cxdh5,1) as f3,min(cxid)-(s