如何在相同产品的标志为真时对一列进行求和

huangapple go评论62阅读模式
英文:

How to sum a column when a flag is true for the same products

问题

我有下面的表格,我无法解决这个规则:

SELECT product_id,
       flag,
       SUM (stock) AS stock
  FROM stock_table
 WHERE product_id = 120104
 GROUP BY product_id,
          flag;

如果有多个相同的 PRODUCT_ID 列和不同的 FLAG 列(YN):
这两行(示例)将合并为一行,FLAG 将等于 YSTOCK 列将值相加为 55

如果对于相同的 PRODUCT_ID 只有一个 FLAGYN),只需将 STOCK 列相加。

我尝试过使用子查询来解决,但无法成功。

英文:

I have the table below and I am not able to resolve this rule:

SELECT product_id,
       flag,
       SUM (stock) AS stock
  FROM stock_table
 WHERE product_id = 120104
 GROUP BY product_id,
          flag;

product_id flag stock
    120104    N    52
    120104    Y     3

If there is more than one identical PRODUCT_ID column and different FLAG column (Y and N):
These two lines (example) will become one, the FLAG will be = Y and the STOCK column will sum the values to 55.

If you only have one FLAG (Y or N) for the same PRODUCT_ID, just sum the STOCK column.

I've tried to solve it with subqueries but I couldn't.

答案1

得分: 1

请尝试以下代码:

SELECT product_id,
       MAX (flag) AS flag,
       SUM (stock) AS stock
  FROM stock_table
 WHERE product_id = 120104
 GROUP BY product_id;
  
product_id flag stock
    120104    Y    55

每当产品只有一个标志时,它将保持不变,当同时存在NY时,它将变为max('N', 'Y') = 'Y'

英文:

Try this:

SELECT product_id,
       MAX (flag) AS flag,
       SUM (stock) AS stock
  FROM stock_table
 WHERE product_id = 120104
 GROUP BY product_id;

product_id flag stock
    120104    Y    55

Whenever it's just a single flag for the product it will stay as is and when there are both N and Y it will become max('N', 'Y') = 'Y'.

huangapple
  • 本文由 发表于 2023年6月6日 02:58:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76409276.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定