我有两张表如下。
产品
+-----------------------------+
| id min_stock is_order |
+-----------------------------+
| p1 5 y |
| p2 6 y |
| p3 5 y |
| p4 0 n |
+-----------------------------+
库存
+-----------------------------+
| id product_id quantity |
+-----------------------------+
| 1 p1 3 |
| 2 p1 5 |
| 3 p2 2 |
+-----------------------------+
现在我想要is_order
状态为y
且其sum(quantity)<= min_stock
的所有记录。
P2
p3
我该怎么做?
答案 0 :(得分:0)
您可以使用APPLY
获取sum_quantity
:
SELECT p.product_id
FROM product p
OUTER APPLY(
SELECT SUM(quantity) AS sum_quantity
FROM Stock
WHERE product_id = p.product_id
)s
WHERE
p.is_order= 'y'
AND (
s.sum_quantity IS NULL
OR s.sum_quantity <= p.min_stock
)
或者,您可以使用LEFT JOIN
和SUM
以及HAVING
:
SELECT p.product_id
FROM product p
LEFT JOIN Stock s
ON s.product_id = p.product_id
WHERE
p.is_order = 'y'
GROUP BY p.product_id, p.min_stock
HAVING SUM(ISNULL(s.quantity, 0)) <= p.min_stock
答案 1 :(得分:0)
select p.*
from product p
inner join (
select
product_id, SUM(quantity)quantity
from stock
group by product_id
) s on p.id = s.product_id
where
s.quantity <= p.min_stock
and p.is_order = 'y'
答案 2 :(得分:0)
;with cte(product_id , quantity )
AS
(
select product_id, sum(quantity)
from Stock
group by product_id
)
select * from
Product p
left join cte s on p.product_id = s.product_id
where p.order_status = 'y' and min_stock <> 0
and isnull(s.quantity,-1) < p.min_stock
答案 3 :(得分:0)
CREATE TABLE #product
(id varchar(2), min_stock int, is_order varchar(1))
;
INSERT INTO #product
(id, min_stock, is_order)
VALUES
('p1', 5, 'y'),
('p2', 6, 'y'),
('p3', 5, 'y'),
('p4', 0, 'n')
;
CREATE TABLE #Stock
(id int, product_id varchar(2), quantity int)
;
INSERT INTO #Stock
(id, product_id, quantity)
VALUES
(1, 'p1', 3),
(2, 'p1', 3),
(3, 'p2', 2)
;
select b.id from
(select product_id,sum(quantity) sum from #Stock group by product_id) a
right join #product b on a.product_id=b.id
where isnull(a.sum,0)<=b.min_stock and b.is_order='y'