SQLite:在一个表中计算两个日期时间戳

时间:2013-07-30 01:28:30

标签: sqlite count group-by epoch

我试图多次修改某个项目或在某个日期创建。

表格如下:

sqlite> select date_modified, date_created from table
1374084096000000000|1334159913000000000
1338386443000000000|1334159913000000000
1366221700000000000|1334159913000000000
1345654859000000000|1334159913000000000

自EPOCH以来,这两个字段均以纳秒为单位。我转换它:

sqlite> select date((DATE_CREATED/1000000000), 'unixepoch', 'localtime'), date((DATE_MODIFIED/1000000000), 'unixepoch', 'localtime') from table;
2012-04-11|2013-07-17
2012-04-11|2012-05-30
2012-04-11|2013-04-17
2012-04-11|2012-08-22

我目前运行两个查询,如下面的一个(一个使用date_modified,另一个使用date_created)。

sqlite> select
   ...>  date((DATE_MODIFIED/1000000000), 'unixepoch', 'localtime') as "Date",
   ...>  count(date((DATE_MODIFIED/1000000000), 'unixepoch', 'localtime')) as "Modified Count"
   ...> from 
   ...>  table
   ...> group by 
   ...>  Date
   ...> limit 10;
2012-04-05|32
2012-04-10|271
2012-04-11|903
2012-04-12|146

如何同时计算两者并显示每个动作在约会中发生的次数?请记住,有些日子没有创建,有些没有修改。我正在寻找这样的东西:

Date|Create_Count|Mod_Count
2012-04-11|0|124
2012-04-12|123|547
2012-04-18|852|674
2012-04-20|741|0

1 个答案:

答案 0 :(得分:0)

试试这个

SELECT d.Dt, sum(CREATED_CNT) "Created", sum(MODIFIED_CNT) "Modified"
FROM
(
  select date((DATE_CREATED/1000000000), 'unixepoch', 'localtime') as "Dt",
  count(*) CREATED_CNT, 0 As MODIFIED_CNT 
  from t 
  group by dt

  UNION ALL

  select date((DATE_MODIFIED/1000000000), 'unixepoch', 'localtime') as "Dt2",
  0 As CREATED_CNT, count(*) As MODIFIED_CNT 
  from t 
  group by dt2
) d
group by dt

OR

SELECT d.Dt, coalesce(CREATED_CNT,0) "Created", coalesce(MODIFIED_CNT,0) "Modified"
FROM
(
 select distinct date((DATE_CREATED/1000000000), 'unixepoch', 'localtime') as "Dt" 
   from t
 UNION 
 select distinct date((DATE_MODIFIED/1000000000), 'unixepoch', 'localtime') as "Dt"
   from t
) d
left outer join 
(
  select date((DATE_CREATED/1000000000), 'unixepoch', 'localtime') as "Dt",
   count(*) CREATED_CNT
   from t
  group by dt
) c on d.dt = c.dt
left outer join 
(
  select date((DATE_MODIFIED/1000000000), 'unixepoch', 'localtime') as "Dt",
   count(*) MODIFIED_CNT
   from t
  group by dt
) m  on d.dt = m.dt

SQL DEMO