首页 > 解决方案 > python编码和创建和SQlite

问题描述

( Jan, Feb, March,.... as variable and 5 levels(d0 to d4)如果我连续 2 个月有任何 d2 级别或一年中的任何月份有任何 d3 或 d4 级别,我想创建一个名为受影响的新列的每个月的文件。我想对 SQLite 做同样的事情

例如

jan...feb, mars April....nov  dec     impacted
0      d2  d2    0       0     0       yes
0      0    0    d3      0     0       yes
0      0    0     0      0     0       no
d4     0    0     0      0     0       yes
0      d2   0     0      0     0       no
d1     d0   d1    d0     d0    d1      no

标签: pythonsqlite

解决方案


如果您想要 SQLite 的 SQL 代码,请使用 aCTE和运算符LIKE

with cte as (
  select *,
    ',' || jan ||',' || feb ||',' || mar ||',' || apr ||',' || may ||',' || jun ||
    ',' || jul ||',' || aug ||',' || sep ||',' || oct ||',' || nov ||',' || dec ||',' months
  from tablename
)
select jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec,
  case when (months like '%,d2,d2,%') or (months like '%,d3,%') or (months like '%,d4,%') then 'yes' else 'no' end impacted
from cte

如果(如您的示例数据)表中没有任何NULLs,则此代码将起作用。如果有,那么您必须使用coalesce().


推荐阅读