如何在24小时内平均SQLite数据库中的项目数?

时间:2011-01-18 21:14:26

标签: sqlite date average

尝试为我们的支持票务系统创建报告,我试图在报告中显示2个结果,显示一天中打开的票数和一天中关闭的票数的滚动平均值。

基本上,查询整个票证表,按照创建票证的个别日期将所有票据分开,计算每个日期的票号,然后平均该号码。

我的朋友给了我这个问题:

SELECT AVG(ticket_count)
FROM (SELECT COUNT(*) AS ticket_count FROM tickets
GROUP BY DATE(created_at, '%Y'), DATE(created_at, '%m'), DATE(created_at, '%d')) AS ticket_part

但它似乎并不适合我。我得到的只是去年创建的门票数量的单一结果。

2 个答案:

答案 0 :(得分:1)

这是最终对我有用的东西:

SELECT round(CAST(AVG(TicketsOpened) AS REAL), 1) as DailyOpenAvg
FROM
(SELECT date(created_at) as Day, COUNT(*) as TicketsOpened
FROM tickets
GROUP BY date(created_at)
) AS X

答案 1 :(得分:0)

查询的中间部分是将表折叠为单行,因此外部部分没有任何内容可以分组。如果没有看到ticket_count的架构,很难准确说出你需要什么,但我猜想我会试试这个:

SELECT
  AVG(CAST(TicketsOpened AS REAL))  -- The cast to REAL ensures that { 1, 2 } averages to 1.5 rather than 1
FROM
  (
  SELECT
    CAST(created_at AS DATE) AS Day  -- The cast to DATE truncates any time element; if you're storing date alone, you can omit this
    COUNT(*) AS TicketsOpened
  FROM
    ticket_count
  GROUP BY
    CAST(created_at AS DATE)
  ) AS X

希望有所帮助!