下面给出了我的表
create table batches ( batchid int,free smallint,qty int)
INSERT INTO batches VALUES (2329, 0, 100);
INSERT INTO batches VALUES (2329, 1, 10);
INSERT INTO batches VALUES (2331, 0, 75);
INSERT INTO batches VALUES (2331, 1, 4);
此表将返回
batchid free qty
2329 0 100
2329 1 10
2331 0 75
2331 1 4
需要在栏 qty
上执行划分,即在这种情况下100应该除以10(batchid应该相同) )100/10(这里10是qty
free = 1
)
预期结果
Batchid freelimit
2329 10
2331 18
答案 0 :(得分:1)
WITH Queries (Common Table Expressions)
with a as (
select
batchid,qty
from batches
where free = 0 order by batchid
)
, b as (
select
batchid,qty
from batches
where free = 1order by batchid
)
select
batchid, floor((a.qty/b.qty))::real as freelimit
from a inner join b using(batchid)
答案 1 :(得分:0)
你想在这里自我加入:
WITH d(batchid, free, qty) AS (
VALUES (2329::int, 0::int2, 100::int), (2329, 1, 10),
(2331, 0, 75), (2331, 1, 4)
)
SELECT a.batchid, a.qty/b.qty
FROM d a
JOIN d b ON a.batchid=b.batchid AND b.free=1
WHERE a.free=0;