SUM的子查询问题

时间:2017-06-27 21:01:29

标签: sql sql-server

我遇到的问题是根据项目ID和子查询对两个不同的列进行求和。我希望从2016年1月1日起获得利润和Qtyship的总和,以附加到每个ShipDate的每个Invtid。我提前感谢您的帮助!

电流:

ShipDate   InvtID      Qtyship   Profit
7/19/2016  Item101         4     $20
7/21/2016  Item101         5     $25
7/1/2016   Product411     11     $44
7/1/2016   Product411     14     $56

以下是它的样子:

ShipDate   InvtID      Qtyship   Profit   Total Qtyship   Total Profit
7/19/2016  Item101         4     $20          9                $45
7/21/2016  Item101         5     $25          9                $45
7/1/2016   Product411     11     $44          25               $100
7/1/2016   Product411     14     $56          25               $100

查询代码:

select h.shipdate, h.invcnbr,
l.invtid, l.slsprice, l.qtyship, l.totcost,
l.slsprice*l.qtyship as revenue,
(l.slsprice*l.qtyship)-l.TotCost as Profit
from opsshipper h
join opshipline l on h.shipperid=l.shipperid where h.invcdate>='7/1/2016' 
and l.qtyship<>0 and l.slsprice>0 order by h.invcdate,l.invtid 

3 个答案:

答案 0 :(得分:1)

您可以使用窗口功能:

SELECT  h.shipdate, 
        h.invcnbr,
        l.invtid, 
        l.slsprice, 
        l.qtyship, 
        l.totcost,
        l.slsprice*l.qtyship as revenue,
        (l.slsprice*l.qtyship)-l.TotCost as Profit,
        SUM(l.qtyship) OVER(PARTITION BY l.invtid) [Total Qtyship],
        SUM((l.slsprice*l.qtyship)-l.TotCost) OVER(PARTITION BY l.invtid) [Total Profit]
FROM opsshipper h
INNER JOIN opshipline l 
    ON h.shipperid = l.shipperid 
WHERE h.invcdate >= '20160701' 
AND l.qtyship <> 0 
AND l.slsprice > 0 
ORDER BY h.invcdate,l.invtid;

答案 1 :(得分:0)

以下简单的解决方案应该有效:

;WITH CTE AS(
    SELECT InvtID,SUM(Qtyship) TotalQtyShip,SUM(Profit) TotalProfit
    FROM OpsShipper 
    WHERE ShipDate>='2016-07-01'
)
SELECT a.ShipDate,a.InvtID,a.QtyShip,a.Profit,c.TotalQtyShip,c.TotalProfit
FROM OpsShipper a JOIN CTE c ON c.InvtID=a.InvtID
WHERE ShipDate>='2016-07-01';

答案 2 :(得分:0)

尝试从您提供的表格详细信息中获取输出。 你可以使用如下的简单查询从7/1/16开始获得Profit和Qtyship的总和。

我用来生成所需输出的查询:

create table shipment(
ShipDate datetime,
InvtID varchar(50),
QtyShip int,
Profit money
)

insert into shipment
values
('7/19/2016','Item101',4,'$20'),
('7/21/2016','Item101',5,'$25'),
('7/1/2016','Product411',11,'$44'),
('7/1/2016','Product411',14,'$56')

select 
    replace(CONVERT(VARCHAR(10), ShipDate, 101),'-','/') as ShipDate,   
    InvtID,
    QtyShip,
    Profit,
    SUM(qtyship) over(partition by invtid) as TotalQtyShip,
    SUM(profit) over (partition by invtid) as TotalProfit
from shipment
where ShipDate > '07/01/2016'

输出: enter image description here