来自多个表的总和?

时间:2018-08-31 07:40:03

标签: sql tsql sum

我正在写一个查询给同事,该同事将研究一系列产品。 查看已售出哪些产品以及已售出多少产品给哪个客户。

我已完成以下查询:

SELECT T0.[DocNum] AS "Invoice Number"
     , T0.[CardName] AS "Customer Name"
     , T1.[ItemCode] AS "Item Code"
     , T1.[Quantity] AS "Quantity" 
FROM OINV T0
    INNER JOIN INV1 T1 ON T0.[DocEntry] = T1.[DocEntry]
    INNER JOIN OITM T2 ON T1.[ItemCode] = T2.[ItemCode]
WHERE T2.[QryGroup7] = 'Y' AND (T0.DocDate>='[%0]' and T0.DocDate<='[%1]')
ORDER BY T0.[CardName], T1.[ItemCode]

要在此添加一些注释... DocDate [%0]是SAP B1的参数,并且可以删除SELECT中的发票编号...这已作为参考添加,直到我解决为止这个问题。

我尝试选择Docnum / Cardname /作为MAX,将Number作为SUM,然后将其添加到GROUP BY部分。

如果我要运行此查询,它将显示以下内容...

Andy - Milk - 40
Andy - Milk - 40
Andy - Milk - 20
Bob - Carrots - 30
Bob -Carrots - 50 

我想将“卡名和商品代码”区别对待,但加总“数量” 带回

的结果
"Andy - milk - 100"
"Bob - Carrots - 80" 

我周围有个不错的Google,似乎找不到任何能起作用的东西,而我尝试过的事情却没有改变。

1 个答案:

答案 0 :(得分:1)

尝试以下进行汇总汇总

SELECT T0.[CardName] AS "Customer Name"
, T1.[ItemCode] AS "Item Code"
, sum(T1.[Quantity]) AS "Quantity" 
FROM OINV T0  INNER JOIN INV1 T1 ON T0.[DocEntry] = T1.[DocEntry] INNER JOIN OITM T2 ON T1.[ItemCode] = T2.[ItemCode]
WHERE T2.[QryGroup7] = 'Y' AND (T0.DocDate>='[%0]' and T0.DocDate<='[%1]')
group by T0.[CardName],T1.[ItemCode]
ORDER BY T0.[CardName], T1.[ItemCode]