首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SQL分组依据计算

问SQL分组依据计算
EN

Stack Overflow用户
提问于 2017-06-20 04:36:19
回答 2查看 54关注 0票数 0

提前谢谢..

代码语言:javascript
复制
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”列中(请参见下图)

我已经输入了‘购买’,‘发行’,‘退货’和‘损坏’作为数据。

实际上,我只需要Sum(nos) - Issue + Return - Damage这样的值,并在查询中使用相同的Group by字段,而不是购买和Sum(areasqft)。

EN

回答 2

Stack Overflow用户

发布于 2017-06-20 04:43:17

您应该能够在sum中使用下面的if语句对Issue和Damage的值进行求反。

代码语言:javascript
复制
    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
票数 0
EN

Stack Overflow用户

发布于 2017-06-20 04:53:13

首先,按TransactionThrough分组:

代码语言:javascript
复制
   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;

然后否定:

代码语言:javascript
复制
create view negByTT as 
select 
transactionthrough,
-width as width, 
-thickness as thickness
-- and for each other column
from byTT;

然后根据您关心的交易类型进行求和,并使用适当的符号:

代码语言:javascript
复制
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" 
);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44639523

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档