sum子句用别名来计算总数?

时间:2014-01-03 15:04:27

标签: sql sql-server sql-server-2008

ALTER PROCEDURE [dbo].[K_FS_GetFeedDivisionReport] 
@orderno varchar(50)
AS
BEGIN

SET NOCOUNT ON;
select OT.OrderNo,FT.Feedtype,ModeofPack='Plastic',BG.Bagtype,OD.Numofbags,   
(OD.numofbags*BG.Bagtype) as TotalQty,sum(TotalQty) as Total from  
K_FS_OrderconfirmDetails OD
inner join K_FS_bagtype BG on OD.bagtype=BG.sno
inner join k_FPS_FeedType FT  on FT.sno=OD.feedtype
inner join K_FS_OrderDetails OT on OT.sno = OD.orderno where OD.orderno = @orderno
group by  OT.OrderNo,FT.Feedtype,BG.Bagtype,OD.Numofbags
END

我在这里计算TotalQty,我想计算TotalQty的总和,但TotalQty是别名 是否可能?其他明智的我如何解决它...请帮助我...

4 个答案:

答案 0 :(得分:2)

您可以使用子查询来实现此目的。 以这种方式修改select语句:

  select OT.OrderNo,FT.Feedtype,ModeofPack='Plastic',BG.Bagtype,OD.Numofbags,   
       (OD.numofbags*BG.Bagtype) as TotalQty,
       (select SUM(OD.numofbags*BG.Bagtype) 
        from K_FS_OrderconfirmDetails OD inner join
        K_FS_bagtype BG on OD.bagtype=BG.sno ) 
        as Total
  from K_FS_OrderconfirmDetails OD
        inner join K_FS_bagtype BG on OD.bagtype=BG.sno
        inner join k_FPS_FeedType FT  on FT.sno=OD.feedtype
        inner join K_FS_OrderDetails OT on OT.sno = OD.orderno where OD.orderno = @orderno
  group by  OT.OrderNo,FT.Feedtype,BG.Bagtype,OD.Numofbags 

这将计算最后一列中所有内容的总和。

答案 1 :(得分:1)

是的,你可以这样做:

ALTER PROCEDURE [dbo].[K_FS_GetFeedDivisionReport] 
@orderno varchar(50)
AS
BEGIN

SET NOCOUNT ON;
select OT.OrderNo,FT.Feedtype,ModeofPack='Plastic',BG.Bagtype,OD.Numofbags,   
(OD.numofbags*BG.Bagtype) as TotalQty,sum(OD.numofbags*BG.Bagtype) as Total from  
K_FS_OrderconfirmDetails OD
inner join K_FS_bagtype BG on OD.bagtype=BG.sno
inner join k_FPS_FeedType FT  on FT.sno=OD.feedtype
inner join K_FS_OrderDetails OT on OT.sno = OD.orderno where OD.orderno = @orderno
group by  OT.OrderNo,FT.Feedtype,BG.Bagtype,OD.Numofbags,OD.numofbags*BG.Bagtype
END

如果每行需要totalQty,则应使用子查询:

ALTER PROCEDURE [dbo].[K_FS_GetFeedDivisionReport] 
    @orderno varchar(50)
    AS
    BEGIN

    SET NOCOUNT ON;
    select OT.OrderNo,FT.Feedtype,ModeofPack='Plastic',BG.Bagtype,OD.Numofbags,   
    (OD.numofbags*BG.Bagtype) as TotalQty,
    Total = (Select Sum (OD.numofbags*BG.Bagtype) from  K_FS_OrderconfirmDetails OD
    inner join K_FS_bagtype BG on OD.bagtype=BG.sno
    inner join k_FPS_FeedType FT  on FT.sno=OD.feedtype
    inner join K_FS_OrderDetails OT on OT.sno = OD.orderno where OD.orderno = @orderno)

 from  
    K_FS_OrderconfirmDetails OD
    inner join K_FS_bagtype BG on OD.bagtype=BG.sno
    inner join k_FPS_FeedType FT  on FT.sno=OD.feedtype
    inner join K_FS_OrderDetails OT on OT.sno = OD.orderno where OD.orderno = @orderno
    group by  OT.OrderNo,FT.Feedtype,BG.Bagtype,OD.Numofbags,OD.numofbags*BG.Bagtype
    END

答案 2 :(得分:0)

你不能这样做:      SUM(OD.numofbags * BG.Bagtype)为TotalQty,sum(TotalQty)为总计

答案 3 :(得分:0)

如果你想要这些总数你需要在numofbags等上删除这个组,那么当你开始对你的计算值进行分组的那一刻,你的nolonger计算一个完整的总和。