Pergunta

I am trying to get a number of times an item was modified or created on a date.

The table looks like this:

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

Both fields are in nanoseconds since EPOCH. I convert it with:

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

I currently run two queries like the one below (one with date_modified and one with 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

How can I count both at the same time and show how many times each action occurred on a date? Keep in mind there will be some days with no created and some with no modified. I am looking for something like this:

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
Foi útil?

Solução

Try this

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top