我知道这是一个复杂的查询,因此我为此提供了一个单独的列,但是该列包含将近99%的null值(这是非常低效的),因此我想知道是否有可能这样做查询。
我有这样的桌子:
TransactionId | Value | ProductId
1 3 2
2 2 2
3 1 2
4 0 4
5 0 4
6 0 4
7 3 7
8 3 7
9 1 7
10 0 3
11 0 3
12 0 3
13 5 1
14 2 1
15 3 1
16 0 4
17 0 4
18 0 4
现在查询的是,如果对于3个连续产品ID,对应的值为0(按TransactionId ASC的顺序),那么对于ProductId
,它将被计为1,即
ProductId | Count
4 2
3 1
我们如何查询呢?
一个可选的简短问题:p
如果我的列大多具有空值,可以吗?
答案 0 :(得分:2)
在最新版本的SQLite中,您可以使用map
/ console.log
:
lag()
答案 1 :(得分:0)
首先使用CTE获取具有3个连续0的行,然后在表中仅包含1(因此将仅计数1):
with
cte as (
select * from (
select *,
lag(transactionid) over (order by transactionid) previd,
lead(transactionid) over (order by transactionid) nextid,
lag(productid) over (order by transactionid) prevprodid,
lead(productid) over (order by transactionid) nextprodid,
lag(value) over (order by transactionid) prevvalue,
lead(value) over (order by transactionid) nextvalue
from tablename
) t
where
productid = prevprodid and productid = nextprodid and
coalesce(value, 0) = 0 and coalesce(prevvalue, 0) = 0 and coalesce(nextvalue, 0) = 0
),
triples as (select previd id from cte union all select nextid from cte)
select productid, count(*) counter
from tablename
where transactionid not in (select id from triples)
group by productid
请参见demo。
结果:
| ProductId | counter |
| --------- | ------- |
| 1 | 3 |
| 2 | 3 |
| 3 | 1 |
| 4 | 2 |
| 7 | 3 |