1、我做了一个查询,数据来源于SQL里的一个视图,但是查询结果是汇总的数量、金额,现在想要根据查询结果自动计算单价
   ——但要考虑当汇总的记录数量为0时,单价则也为0;反之单价=金额/数量
2、查询的结果想在第一列根据查询的记录自动增加序号
   序号规则为:0001,0002,0003……,根据查询的记录数自动增加

解决方案 »

  1.   

    1,为你的查询添加一个数据计算字段sprice在oncaluefield事件中编写如下代码
      if 数量=0  then sprice=0
      else sprice=金额/数量 
    2.可以试着用临时表
      

  2.   

    数据库如果用的是 SQL server 2005 可以用以下语句SELECT RANK() OVER (ORDER BY 主键字段名 DESC) AS 序号,
       数量,金额,(case when 数量 = 0 then 0 else 金额/数量 end) as 单价
    FROM 表名
      

  3.   

    或者建临时表create table tmpTable (序号 int identity(100,10) PRIMARY KEY, 数量 real, 金额 real, 单价 real)insert into tempTable (数量, 金额, 单价) select 数量,金额,(case when 数量 = 0 then 0 else 金额/数量 end) as 单价 FROM 表名select * from tempTable drop table tempTable 
      

  4.   

     先查询最后的ID号在加1
          ADOQuery1.Close;
          ADOQuery1.SQL.Clear;
          ADOQuery1.SQL.Add('select top 1 ID from table ORDER BY ID DESC');
          ADOQuery1.Open;
          kvalue:=ADOQuery1.fieldbyname('ID').AsString;
          kvalue:=floattostr(strtofloat(kvalue)+1);
      

  5.   

    全部用SQL语句就可以了第二个问题:select row_number() over (order by ID ) as rowid,* from ORDER
      

  6.   

    第二个问题终于解决了:
    procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumn; State: TGridDrawState);
    var
    s:string;
    begin
      if   Column.Index   =   0   then   
          with   DBGrid1.Canvas   do   
              begin   
                  FillRect(Rect);
                  s:='000'+IntToStr(DBGrid1.DataSource.DataSet.RecNo);
                  TextOut(Rect.Left+2, Rect.Top+2, copy(s,Length(s)-3,4));
              end;
    end;