SQL Group按计算

时间:2017-06-19 20:36:19

标签: sql ms-access

提前致谢..

SELECT width, thickness, lengthfeet, lengthinch, Sum(nos), Sum(areasqft)
FROM materialsdetails
WHERE materialcode='" & Me.txtMaterialCode.Text & "'
GROUP BY width, thickness, lengthfeet, lengthinch
ORDER BY width, thickness, lengthfeet, lengthinch

我使用上面的代码按组获取字段'nos'和'areasqft'的总和。

在'transactionthrough'列中,(请参阅图片)enter image description here我已输入'Purchase','Issue','Return'和'Damage'作为数据。

实际上,我只需要值Sum(nos)Sum(areasqft),而不是Group by和{{1}} 购买 - 发行+退货 - 在查询中使用相同的{{1}}字段进行损坏。

2 个答案:

答案 0 :(得分:0)

您应该能够使用下面的if语句来否定问题和损害的值。

    SELECT  width
        ,thickness
        ,lengthfeet
        ,lengthinch
        ,SUM(nos*iif(or(transactionthrough="Issue",transactionthrough="Damage"),-1,1))
        ,SUM(areasqft*iif(or(transactionthrough="Issue",transactionthrough="Damage"),-1,1))
FROM materialsdetails
WHERE materialcode = '" & Me.txtMaterialCode.Text & "'
GROUP BY    width
        ,thickness
        ,lengthfeet
        ,lengthinch
ORDER BY width
        ,thickness
        ,lengthfeet
        ,lengthinch

答案 1 :(得分:0)

首先,按TransactionThrough分组:

   create view byTT as 
    SELECT 
    transactionthrough,
    sum(width) as width, 
    sum(thickness) as thickness,
    -- etc for each column you care about
    FROM materialsdetails
    WHERE -- whatever where clause you want
    group by transactionthrough;

然后否定:

create view negByTT as 
select 
transactionthrough,
-width as width, 
-thickness as thickness
-- and for each other column
from byTT;

然后按照您关心的交易类型求和,并使用适当的符号:

select sum(width), sum(thickness) from (
  select width, thickness
  from byTT where transactionthrough = "Purchase" 
    or transactionthrough = "Return" 
  union select width, thickness
  from negByTT where transactionthrough = "Issue"
    or transactionthrough = "Damage" 
);