注册 登录
编程论坛 SQL Server论坛

如何写查询语句呢?

hljzch 发布于 2013-10-08 11:09, 552 次点击
表内的数据如下:
客户编码    商品编码    数量    单价
1            1            10    2.48
1            2            11    1.48
1            1            12    2.36
2            1            23    2.79
2            1            13.8  2.88
想产生如下的报表:
客户编码    商品1 数量2    金额2    商品2    数量2    金额2  
1            1    22        XXX        2        11    XXX
2            1    36.8      XXX
每客户一行,商品数不定,有可能几种,有可能没有,金额为数量*单价
哪个高手指定一下?
7 回复
#2
Sicgl2013-10-08 14:23
不懂....标记一下!
#3
volte2013-10-08 14:42
聚合函数查询
select 客户编码, 商品编码,  sum(数量), sum(单价*数量)
from 原始表
group by 客户编码,商品编码
#4
jxyga1112013-10-08 15:41
这个问题我之前也提过,你找找,,我忘记在哪了,有答案的
#5
jxyga1112013-10-08 15:50
create table table1
(
    id char(3) not null primary key,
    name varchar(10),
    sex bit
)
go
create table table2(id char(3), name varchar(10), sex bit, id2 char(3), name2 varchar(10), sex2 bit)
insert into table1
values('001','a',0)
insert into table1
values('002','b',0)
insert into table1
values('003','c',1)
insert into table1
values('004','d',0)
insert into table1
values('005','e',1)










declare mycur cursor
for select * from table1
open mycur
declare @id char(3),
        @name varchar(10),
        @sex bit,
        @id2 char(3),
        @name2 varchar(10),
        @sex2 bit,
        @i int
        set @i =1
fetch next from mycur
into @id,@name,@sex
while @@fetch_status=0
begin  
      if @i%2 <>0
      begin
         if @i <> 5
         begin
             fetch next from mycur
             into @id2,@name2,@sex2   
             insert into table2      
             values(@id,@name,@sex,@id2,@name2,@sex2)         
         end
         else
         begin
            insert into table2(id,name,sex)  
            values(@id,@name,@sex)
         end         
         set @i = @i+1
      end
      else
      begin
          fetch next from mycur
          into @id,@name,@sex
          set @i = @i+1
      end
end
close mycur
deallocate mycur

小仙写的
#6
Sicgl2013-10-08 16:13
好像也不难!
只有本站会员才能查看附件,请 登录


[ 本帖最后由 Sicgl 于 2013-10-9 03:35 编辑 ]
#7
hljzch2013-10-08 16:47
聚合函数的我写完了,结果是
1    1    22
1    2    10
2    1    36.8
是三行数据,不是我说的两行数据
怎样实现只显示两行呢?
#8
jxyga1112013-10-09 08:39
你认为你这种要求一句代码能搞定
1