SQL Sumif函数/ GROUP BY&和?

时间:2016-03-18 12:31:15

标签: sql db2 ibm-midrange sumifs

我已经被困在这一段时间了,并且在我的生活中不能理解为什么SQL没有通过我想要的东西。看起来很简单,我知道它很简单,但我找不到合适的数字。

我有一些代码从我们的数据库中的连接表中提取数据,显示客户编号,购买的产品,购买日期以及产品价格和该产品系列的数量。当我在日期和GROUP之间进行日期设置时,它可以完美地运行并提取所有正确的信息。

我想要的是GROUP by product,总结每个客户在日期范围内购买的产品数量。当我试图求和(SIL.ILQTY)总和超过计算这个值.......我尝试过用CASE也失败了。我有下面的代码并过滤了记录以使测试更容易,因此只显示一个产品和一个客户,该产品有7个购买日期。

以下代码按日期显示有效的记录:

SELECT SIH.SICUST, SIL.ILPROD, date(SIL.ILDATE), SIL.ILNET, SIL.ILQTY,
       SIL.ILQTY*SIL.ILNET, SIH.SICUST || ' ' ||  rtrim(SIL.ILPROD) || ' '
FROM NWBAKERS.BPCSF.IIM IIM,
     NWBAKERS.BPCSF.SIH SIH,
     NWBAKERS.BPCSF.SIL SIL
WHERE SIH.SIINVN = SIL.ILINVN
  AND IIM.IPROD = SIL.ILPROD
  AND ((date(SIL.ILDATE) between '02/01/2016' and '02/29/2016'))
  and SIL.ILWHS ='PR'
  and SIL.ILQTY > '0'
  and SIH.SICUST = '40634'
  and SIL.ILPROD = '81039'
GROUP BY SIH.SICUST, SIL.ILPROD, date(SIL.ILDATE), SIL.ILQTY, SIL.ILNET

问题是当我从select语句中的group by语句和sum(SIL.ILQTY)中删除日期(SIL.ILDATE)以获取购买唯一产品总数的唯一客户编号(ILQTY) )在指定的日期范围内。

任何人都可以指出我正确的方向吗????

上面的示例数据图片:

image

在select语句中从Group by和sum(ILQTY)中删除Date的数据:

image2

Desired result for one product by customer

Image shows the added fields for invoice number and order number, giving duplicate lines for date/quantity/invoice as order number are different. The sum of these qty values is what my SQL code was summing previously.

2 个答案:

答案 0 :(得分:1)

我找到了一种方法让它工作,与我想的有点不同,但它运作良好并返回完美的信息......感谢所有试图帮助解决这个问题的人!

SELECT T.SICUST, T.ILPROD, SUM(Quantity) as Num_Products 
FROM
(
SELECT SIH.SICUST, SIL.ILPROD, SIL.ILNET, MAX(SIL.ILQTY) as Quantity
FROM NWBAKERS.BPCSF.IIM IIM,
     NWBAKERS.BPCSF.SIH SIH,
     NWBAKERS.BPCSF.SIL SIL
WHERE SIH.SIINVN = SIL.ILINVN
AND IIM.IPROD = SIL.ILPROD
AND ((date(SIL.ILDATE) between '02/01/2016' and '02/29/2016'))
and SIL.ILWHS ='PR'
and SIL.ILQTY > '0'
and SIH.SICUST = '40634'
and SIL.ILPROD = '81039'
GROUP BY SIH.SICUST, SIL.ILPROD, SIL.ILNET, SIL.ILINVN
) AS T
GROUP BY T.SICUST, T.ILPROD

问题是我们表格中的重复行是在同一发票ID上有多个订单,我从中获取了最大值,然后在group by语句中删除了日期后得到了这些值的总和。希望别人可能会觉得这很有用!

答案 1 :(得分:0)

如果您想知道您的客户只需要一个数量/价格多少次,并想要总价值,您可以尝试这样的事情

 SELECT SIH.SICUST, SIL.ILPROD, date(SIL.ILDATE), SIL.ILNET, SIL.ILQTY,
    sum(SIL.ILQTY)*sum(SIL.ILNET) as TotalValue, count(*) as HowManyTimes,
    SIH.SICUST || ' ' ||  rtrim(SIL.ILPROD) || ' '
    FROM NWBAKERS.BPCSF.IIM IIM,
         NWBAKERS.BPCSF.SIH SIH,
         NWBAKERS.BPCSF.SIL SIL
    WHERE SIH.SIINVN = SIL.ILINVN
    AND IIM.IPROD = SIL.ILPROD
    AND ((date(SIL.ILDATE) between '02/01/2016' and '02/29/2016'))
    and SIL.ILWHS ='PR'
    and SIL.ILQTY > '0'
    and SIH.SICUST = '40634'
    and SIL.ILPROD = '81039'
    GROUP BY SIH.SICUST, SIL.ILPROD, SIL.ILDATE, SIL.ILQTY, SIL.ILNET

我没有试过对不起..