使用连接列数据访问Sql组

时间:2016-11-04 18:10:08

标签: sql ms-access-2010

我有table1

表1

 PNAME      PBS    Vkg
   p1       ABC    2
   p2wt     ABC    3
   p3       EFG    1
   p3wtke   EFG    1

分组

 Select PNAME, PBS,Sum(Vkg) As swt from table1 group by PNAME,PBS;

这给了我像上表一样的东西。但是,如果像

那样出现相同的PBS,我该如何连接PNAME
  PNAME       PBS    Vkg
   p1-p2wt    ABC    5
   p3-p3wtke  EFG    2 

2 个答案:

答案 0 :(得分:0)

对于您的特定示例,这恰好起作用:

Select min(PNAME) & '-' & max(PNAME), PBS, Sum(Vkg) As swt
from table1
group by PBS;

然而,我不确定这是否是您问题的一般解决方案。

编辑:

使用iif()来处理值相同的情况:

Select iif(min(Pname) = max(Pname), min(Pname),
           min(PNAME) & '-' & max(PNAME)
          ),
       PBS, Sum(Vkg) As swt
from table1
group by PBS;

答案 1 :(得分:0)

以下是一般解决方案:

declare @Table1 table(ID int identity(1,1), PNAME varchar(50), PBS varchar(50), Vkg int)
insert into @Table1
select PNAME, PBS, Vkg from Table1

declare @t table(PNAME varchar(100), PBS varchar(100));
declare @num int = 1
declare @pname varchar(100)=''
while(@num <= (select count(*) from @Table1))
    Begin
        set @pname=(select PNAME from @Table1 where ID = @num);
        while((select PBS from @Table1 where ID=@num)=(select PBS from @Table1 where ID=@num+1))
        begin
            Set @pname = @pname + (select PNAME from @Table1 where ID=@num+1)
            set @num = @num +1
        end
        insert into @t values(@pname, (select PBS from @Table1 where ID=@num));
        set @num = @num +1
    End
select t.PNAME, t.PBS, T1.Vkg from @t t
left join (select PBS, sum(Vkg) as Vkg from @Table1 Group by PBS) T1 ON t.PBS=t1.PBS