MySQL - 使用分组条件查询

时间:2016-04-20 20:36:34

标签: mysql sql

enter image description here

嗨,

我有像上面的图片一样的行表,我想总结所有行的QTY,但我需要排除AISLE = POS和QTY<的行。 0在同一行。

我试图得到我想要的但我无法找到解决方案:

SELECT
  ROUND(SUM(QTY),
  2) AS INVENTORY
FROM
  INV_QTY_LOCATION
WHERE
  PRODUCT = 143459 AND AISLE != 'PHY' AND AISLE != 'RET' AND case when AISLE = 'POS' AND QTY > 0

另一次尝试

SELECT
  ROUND(SUM(QTY),
  2) AS INVENTORY
FROM
  INV_QTY_LOCATION
WHERE
  PRODUCT = 143459 AND AISLE != 'PHY' AND AISLE != 'RET' AND (AISLE = 'POS' AND QTY > 0)

在这种特殊情况下,结果应该是161。

解决方案

SELECT
  ROUND(
    SUM(
      CASE WHEN(AISLE = 'POS' AND QTY > 0) OR AISLE != 'POS' THEN QTY ELSE 0
    END
  ),
  2
) AS INVENTORY
FROM
  INV_QTY_LOCATION
WHERE
  PRODUCT = 143459 AND AISLE != 'PHY' AND AISLE != 'RET'

3 个答案:

答案 0 :(得分:2)

我想指出NOT IN对此查询有帮助:

WHERE PRODUCT = 143459 AND
      AISLE NOT IN ('PHY', 'RET') AND
      (AISLE <> 'POS' OR QTY > 0)

注意:这假定AISLE永远不会NULL

或者,或者:

WHERE PRODUCT = 143459 AND
      AISLE NOT IN ('PHY', 'RET') AND
      NOT (AISLE = 'POS' AND QTY > 0)

答案 1 :(得分:1)

你的第二个陈述几乎是正确的,但既然你试图&#34;排除AISLE = POS&#34;,那么它应该是AISLE <> 'POS'

SELECT
  ROUND(SUM(QTY),
  2) AS INVENTORY
FROM
  INV_QTY_LOCATION
WHERE
  PRODUCT = 143459 AND AISLE != 'PHY' AND AISLE != 'RET' AND (AISLE <> 'POS' OR QTY > 0)

答案 2 :(得分:0)

尝试使用

AND (AISLE <> 'POS' OR QTY >= 0)