【问题标题】:SQLITE DISTINCT COUNT within a strftime statement throwing errorstrftime 语句中的 SQLITE DISTINCT COUNT 引发错误
【发布时间】:2020-02-18 06:27:41
【问题描述】:

我在 Jupyter 笔记本中通过 Pandas 在 SQLite 中查询。

以下查询按预期运行,但我希望 dayofweek_count 计算每个工作日的出现次数。每天可以有多个条目(即星期一 2/17/20 可能有 4 个条目,但我只想计算一次 2/17/20 星期一)

df_total_weekday=pd.read_sql_query("SELECT CASE cast(strftime('%w', event_date) as integer)" 
    "when 0 then 'Sunday'"
    "when 1 then 'Monday'"
    "when 2 then 'Tuesday'"
    "when 3 then 'Wednesday'"
    "when 4 then 'Thursday'" 
    "when 5 then 'Friday'"
    "else 'Saturday' end as dayofweek"
    ",COUNT(strftime('%w', event_date)) as dayofweek_count"
    ",SUM(quantity) as total_quantity FROM subscription_data GROUP BY 1 ORDER BY strftime('%w', event_date)",conn,parse_dates=['event_date'])

但此查询在 DISTINCT 附近引发语法错误,但我似乎无法弄清楚原因。我已经尝试过 DISTINCT (event_date) 以及 DISTINCT event_date。

df_total_weekday=pd.read_sql_query("SELECT CASE cast(strftime('%w', event_date) as integer)" 
        "when 0 then 'Sunday'"
        "when 1 then 'Monday'"
        "when 2 then 'Tuesday'"
        "when 3 then 'Wednesday'"
        "when 4 then 'Thursday'" 
        "when 5 then 'Friday'"
        "else 'Saturday' end as dayofweek"
        ",COUNT(strftime('%w',DISTINCT event_date)) as dayofweek_count"
        ",SUM(quantity) as total_quantity FROM subscription_data GROUP BY 1 ORDER BY strftime('%w', event_date)",conn,parse_dates=['event_date'])

我错过了什么?

【问题讨论】:

  • 考虑创建一个minimal reproducible example。我建议提供一个定制的玩具数据库,形状为几行 creat table ...insert ...,可以在 SQLite 命令行工具中使用。我怀疑 DISTINCT 放错地方了,想尝试一下。

标签: pandas sqlite strftime


【解决方案1】:
COUNT(strftime('%w',DISTINCT event_date))

这是一个语法错误,因为strftime() 不理解DISTINCT;它不是聚合函数(并且对于聚合函数,它仅适用于具有单个参数的函数)。 COUNT(strftime(...)) 无论如何都没有多大意义,除非您的某些 event_date 值不是可接受的日期/时间字符串(这将使 strftime() 返回 NULL)。

【讨论】:

  • 此查询的目标是获取星期几和每个相关的计数以及附加到每个条目的相关数量的总和。每个日期可以有多个(或没有)条目。那么是否可以有一个查询输出:SUNDAY, 43, 12909,其中 43 是星期日的唯一日期数,12909 是附加到星期日日期的数量之和?
猜你喜欢
  • 1970-01-01
  • 2015-12-15
  • 2021-12-18
  • 1970-01-01
  • 1970-01-01
  • 2016-08-18
  • 1970-01-01
  • 2016-06-10
  • 1970-01-01
相关资源
最近更新 更多