小弟觉得是有点挑战性的SQL语句,特急!!在线等,请赐句!!!!!

linjwa 2006-06-09 10:01:56
表结构非常简单,如下:

色卡,箱号,数量
0001,X001,10
0001,X002,20
0001,X003,15
0002,X001,30


要求:统计出各色卡的箱号数,但是!!!!!!!!!!
色卡不一样但箱号一样的(比如第1条和第4条),
只取数量最大的一条加入该色卡箱号数的统计.

统计后的结果应该如下:
色卡,箱号数
0001,2 //虽然0001的箱号有3条记录,但箱号X001在第4条中已存在,且数量没有第4条的大,所以不统计
0002,1 //箱号X001的数量比第1条中的数量大,所以统计在此.


...全文
138 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
昵称被占用了 2006-06-10
  • 打赏
  • 举报
回复
考虑数量相等的情况

declare @t table(色卡 varchar(10),箱号 varchar(10),数量 int)
insert into @t select '0001','X001',10
union all select '0001','X002',20
union all select '0001','X003',15
union all select '0002','X001',30
union all select '0002','X004',10
union all select '0003','X001',30
union all select '0003','X004',20

select 色卡,
箱号数=count(*)
from (select * from @t a where 色卡=(select top 1 色卡 from @t where 箱号=a.箱号 order by 数量 desc))a
group by 色卡
youyudejitashou 2006-06-10
  • 打赏
  • 举报
回复
create table #temp4 (色卡 char(4),箱号 char(4),数量 int)

insert into #temp4 select '0001','X001',10 union all
select '0001','X002',20 union all
select '0001','X003',15 union all
select '0002','X001',30

select b.色卡,count(b.箱号) as '箱号数'
from (select * from #temp4 as a where not exists (select 1 from #temp4 where 箱号=a.箱号 and 数量>a.数量)) as b
group by b.色卡
xeqtr1982 2006-06-09
  • 打赏
  • 举报
回复
declare @t table(色卡 varchar(10),箱号 varchar(10),数量 int)
insert into @t select '0001','X001',10
union all select '0001','X002',20
union all select '0001','X003',15
union all select '0002','X001',30

select 色卡,
箱号数=count(*)
from (select * from @t a where not exists(select 1 from @t where 箱号=a.箱号 and 数量>a.数量))a
group by 色卡
LouisXIV 2006-06-09
  • 打赏
  • 举报
回复
--不知道有没有BUG,测试通过

declare @tab table (色卡 char(4),箱号 char(4),数量 int)
insert into @tab
select '0001','X001',10 union all
select '0001','X002',20 union all
select '0001','X003',15 union all
select '0002','X001',30 union all
select '0002','X002',15 union all
select '0002','X004',20

select
色卡,
(
select count(箱号)
from @tab ta1
where ta.色卡=色卡 and 数量=(select max(数量) from @tab where 箱号=ta1.箱号)
) as 箱号数
from @tab ta
group by 色卡

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧