带有GROUP BY的Oracle SELECT语句和多个WHERE子句

时间:2018-05-24 15:37:01

标签: sql oracle

我在选择查询时遇到问题。请参阅下面的示例数据我想选择仓库ID 1没有库存数量的Sku记录,但仓库ID 2和库存有库存数量。 3.不确定我做错了什么?

样本表数据

Sku         WhseId      Qty
============================
ABC-123     1           6
ABC-123     2           3
ABC-123     3           2
XYZ-789     1           0
XYZ-789     2           1
XYZ-789     3           3
DEF-456     1           0
DEF-456     2           0
DEF-456     3           3

QUERY

SELECT Sku, WhseId, Qty
FROM PRODUCTS
WHERE (WhseId = 1 AND Qty < 1)
AND (WhseId = 2 AND Qty > 0
AND (WhseId = 3 AND Qty > 0)
GROUP BY Sku, WhseId, Qty

期望的结果

Sku         WhseId      Qty
============================
XYZ-789     1           0
XYZ-789     2           1
XYZ-789     3           3

6 个答案:

答案 0 :(得分:2)

我认为你实际上想要使用EXISTS:

SELECT Sku, WhseId, Qty
FROM PRODUCTS p
WHERE EXISTS
(SELECT 1
 FROM PRODUCTS p2
 WHERE p.sku = p2.sku
 AND p2.whseid = 1
 AND p2.qty = 0)
AND EXISTS
(SELECT 1
 FROM PRODUCTS p3
 WHERE p.sku = p3.sku
 AND p3.whseid = 2
 AND p3.qty > 0)
AND EXISTS
(SELECT 1
 FROM PRODUCTS p4
 WHERE p.sku = p4.sku
 AND p4.whseid = 3
 AND p4.qty > 0)

答案 1 :(得分:1)

使用聚合和having子句:

SELECT Sku
FROM PRODUCTS
GROUP BY Sku
HAVING SUM(CASE WHEN WhseId = 1 AND Qty < 1 THEN 1 ELSE 0 END) > 0 AND
       SUM(CASE WHEN WhseId = 2 AND Qty > 0 THEN 1 ELSE 0 END) > 0 AND
       SUM(CASE WHEN WhseId = 3 AND Qty > 0 THEN 1 ELSE 0 END) > 0;

答案 2 :(得分:0)

SELECT
   Sku,
   WhseId,
   Qty
FROM
(
   SELECT
      PRODUCTS.*,
      SUM(CASE WHEN WhseId = 1 THEN Qty END) OVER (PARTITION BY Sku)   AS whse1_qty,
      SUM(CASE WHEN WhseId = 2 THEN Qty END) OVER (PARTITION BY Sku)   AS whse2_qty,
      SUM(CASE WHEN WhseId = 3 THEN Qty END) OVER (PARTITION BY Sku)   AS whse3_qty
   FROM
      PRODUCTS
)
  pivotted
WHERE
      whse1_qty < 1
  AND whse2_qty > 0
  AND whse3_qty > 0

答案 3 :(得分:0)

CREATE VIEW get_skus_2 AS
SELECT Sku
FROM PRODUCTS
WHERE Qty>0 AND WhseId=2;

CREATE VIEW get_skus_3 AS
SELECT Sku
FROM PRODUCTS
WHERE Qty>0 AND WhseId=3;

SELECT Sku s, WhseId, Qty
FROM get_skus_2 g2 JOIN get_skus_3 g3 ON g2.Sku = g3.Sku
WHERE s IN (
    SELECT Sku
    FROM PRODUCTS
    WHERE Qty=0 AND WhseId=1);

答案 4 :(得分:0)

一个简单的解决方案:

select sku, whseid, qty
from etst
where sku = 'XYZ-789' and ((whseid = 1 and qty < 1)
or (whseid = 2 and qty > 0)
or (whseid = 3 and qty > 0))
group by sku, whseid, qty;

答案 5 :(得分:0)

如何在Sku上将IN与GROUP BY结合起来?

SELECT Sku, WhseId, Qty
FROM PRODUCTS
WHERE Sku IN ( 
   SELECT Sku
   FROM PRODUCTS
   WHERE WhseId IN (1, 2, 3)
   GROUP BY Sku
   HAVING MAX(CASE WHEN WhseId = 1 THEN Qty END) = 0
      AND MAX(CASE WHEN WhseId = 2 THEN Qty END) > 0
      AND MAX(CASE WHEN WhseId = 3 THEN Qty END) > 0
)
ORDER BY Sku, WhseId;

<强>结果:

Sku     WhseId Qty
------- ------ ---
XYZ-789      1   0
XYZ-789      2   1
XYZ-789      3   3

SQL Fiddle