按组名获取结果与按组名结果截然不同 [英] Get Result by Group name distinict by group name result
问题描述
大家好,我对sql查询有疑问,我有一个表,其中包含类似..
的数据
GrpId  Item
1 芒果
1  Apple
2 主席
2 表
3 电脑
3 电视
4 踏板车
4 汽车
我想通过GrpId获得结果实际上我的表中有6行,但是如果我由GrpId认为,则在一组中有两个项目,所以我想要这样的输出
1 Mango/Apple
2 主席/桌子
3 Computer/T.V
4踏板车/汽车
请帮我解决这个问题
在此先感谢
hi everybody I have a problem with sql query, I have a table having data like..
GrpId  Item
1 Mango
1   Apple
2   Chair
2 Table
3 Computer
3 T.V.
4 Scooter
4   Car
i want to get result by GrpId I have 6 row in my table actualy but if i think by GrpId then there in one group two items so I want output like that
1 Mango/Apple
2 Chair/Table
3 Computer/T.V
4 Scooter/Car
plz help me on this topic
Thanks in advance
推荐答案
尝试通过以下方式进行查找..
grpid Item
----------- ------------------
1 Mango
1 Apple
1 Chair
2 table
2 Computer
3 TV
4 Scooty
4 Car
//尝试了此
//tried this
declare @Inloop int
set @Inloop=1
declare @grpid int
declare @RItems varchar(50)
declare @Counter int
declare @table2 table(inident1 int identity(1,1),items1 varchar(50))
declare @table table(ident int identity(1,1),Number int,grpId int)
insert into @table select Count(grpid),grpId from test8 group by grpid
select @OutCounter=Count(*) from @table
while (@Outloop <=@OutCounter)
begin
create table #table1(inident int identity(1,1),items varchar(50))
select @grpid= grpId from @table where grpId= @Outloop
print @Outloop
insert into #table1 select Item from test8 where grpId = @grpid
select @InCounter=Count(*) from #table1
print @InCounter
print @Inloop
while(@Inloop<=@InCounter)
begin
select @RItems=items from #table1 where inident=@Inloop
if(@Inloop=1)
begin
insert into @table2 values(@RItems)
end
else
begin
Update @table2 set items1=items1+''/''+@RItems where inident1=@Outloop
end
set @Inloop=@Inloop+1
end
drop table #table1
set @InCounter=0
set @Inloop=1
set @Outloop=@Outloop+1
end
select * from @table2
//Result
inident1 items1
----------- -------------------
1 Mango/Apple/Chair
2 table/Computer
3 TV
4 Scooty/Car
这篇关于按组名获取结果与按组名结果截然不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!