基于postgreSql 常用查询报告

这篇文章主要介绍了基于postgreSql 常用查询小结,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧。
 
1. 日期格式转化(参考)
 
1select beg_time, end_time, extract(epoch from to_timestamp(end_time,'yyyy-mm-dd-HH24-MI-SS-US'))-extract(epoch from to_timestamp(beg_time,'yyyy-mm-dd-HH24-MI-SS-US')) from cdb_all_iu_data where beg_time > '2017-09-21'
 
 
注:beg_time, end_time以TEXT形式存储,求时间差时转化为时间戳再相减得到结果(s)
 
2. select * from (中间结果) t
 
select count(*) from (
select chkid, count(*) from abc_table GROUP BY chkid) t
 
 
 
补充:自己写的postgreSQL查询语句
 
我就废话不多说了,大家还是直接看代码吧~
 
import psycopg2
class PostgreConn():
  '''
  数据库连接类
  '''
  def __init__(self, database, user, password, host, port):
    self.conn = psycopg2.connect(database=database, user=user, password=password, host=host, port=port)
    print('数据库连接成功')
    self.cur = self.conn.cursor()
    self.rows = None
 
  def cur(self):
    return self.cur()
 
  def execute(self, sql, fetchone=0):
    self.cur.execute(sql)
    if fetchone:
      self.rows = self.cur.fetchone()
    else:
      self.rows = self.cur.fetchall()
    return self.rows
 
  def close(self):
    self.cur.close()
    self.conn.close()
    print('数据库连接关闭')
 
def select_sql(table, keys, conditions, isdistinct=0):
  '''
    生成select的sql语句
  @table,查询记录的表名
  @key,需要查询的字段
  @conditions,插入的数据,字典
  @isdistinct,查询的数据是否不重复
  '''
  if isdistinct:
    sql = 'SELECT distinct %s ' % ",".join(keys)
  else:
    sql = 'SELECT %s ' % ",".join(keys)
  sql += ' from %s ' % table
  if conditions:
    sql += ' WHERE %s ' % dict_str_and(conditions)
  return sql
【声明】:芜湖站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

相关文章