开发者

convert sqlite to postgres query

Can someone help me convert this sqlite query to a postgres query?

SELECT count(*), count(*), date(date, '-'||strftime('%w',date)||' days') as date
FROM emails as m, contacts as me
WHERE datetime(date) > datetime('2010-08-25')
  and datetime(date) < datetime('2011-08-25')
  and (me.id = m.fr)
  and me.email like '%gmail.com%'
GROUP BY date
ORDER BY date asc

update, I found the answer:

sele开发者_如何学运维ct count(*), (m.date::date - extract(dow from m.date)::int) as dat
from emails as m join contacts as me on m.fr = me.id
where m.date > '2010-08-25'
  and m.date < '2011-08-25'
  and me.email like '%gmail.com%'
group by dat
order by dat


The strftime business was taken care of elsewhere so we only have to sort out the datetime(...) stuff here and compensate for date being a timestamp. And I'll switch to an explicit join condition (rather than the implicit one in the WHERE clause) while I'm here.

select count(*), count(*), m.date::date - extract(dow from m.date)::int as date
from emails as m join contacts as me on m.fr = me.id
where m.date > '2010-08-25'
  and m.date < '2011-08-25'
  and me.email like '%gmail.com%'
group by m.date
order by m.date asc

PostgreSQL can compare timestamps with ISO8601 date strings on its own so you don't need any casting or reformatting for the comparisons.

The two count(*) still look a bit funny to me but I don't know the context that the query is used in so the duplicates might make sense.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜