1. 日期格式转化( 参考 )
1 |
select 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
1 2 |
select count (*) from ( select chkid, count (*) from abc_table GROUP BY chkid) t |
补充:自己写的postgreSQL查询语句
我就废话不多说了,大家还是直接看代码吧~
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
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
def dict_str_and(dictin): '' ' 将字典变成,key=' value ' and key=' value '的形式 ' '' tmplist = [] for k, v in dictin.items(): tmp = "%s='%s'" % (str(k), str(v)) tmplist.append( ' ' + tmp + ' ' ) return ' and ' . join (tmplist)
def fSqlResult(r,key_list): '' ' :param r: 数据库fetchall的结果 :param key_list: 查询字段的keys :return: format SQL Result 格式化数据库查询的结果,转化成包含多个字典的列表格式,即((1,2),(3,4))->[{"key1":1,"key2":2},{"key1":3,"key2":4}] 返回 @dict 查询结果 ' '' mlist=[] l=len(key_list) if r: for item in r: tmp={} for i in range(l): tmp[key_list[i]]=str(item[i]) mlist.append(tmp) return mlist
conn = PostgreConn( 'settle' , 'admin' , 'settle8' , '123.57.285.89' , '5432' ) key_list = [ 'user_id' ] sql = select_sql( 'st_user' , key_list, { 'phone' : '138****' }) print(sql) r = conn. execute (sql) re = fSqlResult(r, key_list) print(re) conn. close () |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。
原文链接:https://www.cnblogs.com/kaituorensheng/p/7588007.html
查看更多关于基于postgreSql 常用查询小结的详细内容...