每个项目编号的值总和?

时间:2018-08-14 09:41:42

标签: sql sql-server

我写了sql server query,它给了我这个结果link

在这里您可以看到ITEMNO在重复,我想要对TOTALQUANTITYUSETOTALQUANTITYSALE两列的itemno求和。 例如,我只希望在每个itemno上输入一个条目,例如ITEMNO 220415在单行中仅显示一次,并且此项目编号的值总和将显示在一行上。希望您理解。

SELECT a.ITEMNO,(COUNT(a.ITEMNO)*a.QTY) as 'Total Quantity USE', 
(COUNT(WR.ITEMEMPNO)*WR.QTY) AS 'Total Quantity Sale'
 FROM InvItems a
  inner join WRKTRANS WR ON WR.ITEMEMPNO=a.ITEMNO
  inner join InvHdr HR ON HR.INVTYPE =a.TYPE
  WHERE a.ITEMNO IS NOT NULL AND a.TYPE='3'
  group by a.ITEMNO,WR.QTY,a.QTY

4 个答案:

答案 0 :(得分:3)

类似的事情应该起作用(基于itemno汇总记录并显示总和)-

;WITH CTE AS (
    SELECT a.ITEMNO,(COUNT(a.ITEMNO)*a.QTY) as 'Total Quantity USE', 
    (COUNT(WR.ITEMEMPNO)*WR.QTY) AS 'Total Quantity Sale'
     FROM InvItems a
      inner join WRKTRANS WR ON WR.ITEMEMPNO=a.ITEMNO
      inner join InvHdr HR ON HR.INVTYPE =a.TYPE
      WHERE a.ITEMNO IS NOT NULL AND a.TYPE='3'
      group by a.ITEMNO,WR.QTY,a.QTY)
    SELECT ITEMNO,SUM([Total Quantity USE]),SUM([Total Quantity Sale])
    FROM CTE
    GROUP BY ITEMNO

答案 1 :(得分:1)

SELECT ItemNo, SUM([Total Quantity USE]) AS "Total Quantity USE", SUM([Total Quantity Sale]) AS "Total Quantity Sale"
FROM (your_query) AS q
GROUP BY ItemNo

答案 2 :(得分:0)

使用整合功能

    select itemno,sum([Total Quantity USE] totalQty),
   sum( [Total Quantity Sale] ) as TotalSale,
   count(itemno) as total_iteam from yourtable t    
    group by  itemno 

答案 3 :(得分:0)

您需要编写多个CTE语句,以便在SELECT语句中具有额外的属性。 @Abhishek代码中的附加内容很少,请检查以下内容。

foo