从PostgreSQL查询中按条件获取行
我有以下查询从func1ID中选择* 如果我这样做:从func110中选择* 我得到:从PostgreSQL查询中按条件获取行,sql,postgresql,Sql,Postgresql,我有以下查询从func1ID中选择* 如果我这样做:从func110中选择* 我得到: rownum date qty 1 1.1.10 -5 2 1.10.10 6 3 2.10.10 6 4 5.10.10 -2 5 6.10.10 -8 如果我从func17中选择* 我明白了 如果我从func16中选择* 我明白了 rownum是根据我的需要在func1中计算的列的顺序。它不是随机编号。假设编号正确 我想写一个
rownum date qty
1 1.1.10 -5
2 1.10.10 6
3 2.10.10 6
4 5.10.10 -2
5 6.10.10 -8
如果我从func17中选择*
我明白了
如果我从func16中选择*
我明白了
rownum是根据我的需要在func1中计算的列的顺序。它不是随机编号。假设编号正确
我想写一个查询,返回一个从下到上查找数量搜索中第一次出现的数量>=0的查询!从最高rownum到最低rownum,并在rownum+1行中为我提供日期。如果没有与数量>=0匹配的行,它将返回第一行的日期。如果根本没有行,则返回NULL
意味着:
从func110中选择*输出应为5.10.10,因为rownum=3是从下至上的第一个数量>=0,而5.10.10是rownum+1中的日期
从func17中选择*输出应为1.1.10,因为没有数量>=0,所以它给出了rownum=1的日期
从func17中选择*由于没有行,因此输出应为空
我怎样才能做到这一点呢?首先从底部看不是负数
t=# with a(i,q) as (values(1,-5),(2,3),(3,-9),(4,-1))
select * from a where i=1 or q>=0 order by case when i=1 then null else i end desc nulls last, q limit 1;
i | q
---+---
2 | 3
(1 row)
所有底片-第一行:
t=# with a(i,q) as (values(1,-5),(2,-3),(3,-9),(4,-1))
select * from a where i=1 or q>=0 order by case when i=1 then null else i end desc nulls last, q limit 1;
i | q
---+----
1 | -5
(1 row)
空集:
t=# with a(i,q) as (select 1,1 where false)
select * from a where i=1 or q>=0 order by case when i=1 then null else i end desc nulls last, q limit 1;
i | q
---+---
(0 rows)
请在func中输入查询…@VaoTsun我不想修改func1我想编写一个查询,用它来提供我需要的日期。
t=# with a(i,q) as (values(1,-5),(2,-3),(3,-9),(4,-1))
select * from a where i=1 or q>=0 order by case when i=1 then null else i end desc nulls last, q limit 1;
i | q
---+----
1 | -5
(1 row)
t=# with a(i,q) as (select 1,1 where false)
select * from a where i=1 or q>=0 order by case when i=1 then null else i end desc nulls last, q limit 1;
i | q
---+---
(0 rows)