sql - postgresql中选择查询的划分

标签 sql postgresql

下面给出了我的表

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

最佳答案

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)

SQLFIDDLE-DEMO

关于sql - postgresql中选择查询的划分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26338231/

相关文章:

json - PostgreSQL 选择到 JSON 数组

php - 如何获取最新数量的sql子查询

php - Importbuddy 内部 500 服务器错误步骤 3

mysql - SQL 查询 - 左连接还是联合?

sql - 下一个可用值 - postgresql

sql - 在 SQL 中如何仅返回匹配日期和月份的记录(忽略年份)

sql - 如何在 shell 脚本中验证更新或选择查询?

SQL 存储过程用 IF-ELSE 修改

hibernate - JDBC 类型 : 2003 没有方言映射

SQL - 使用 Union All 并添加重复项