MySQL 以及 Python 实现排名窗体函数
这里,我用MySQL 以及Python 分别实现了rank 窗体函数。
原始表信息:
t_girl=# \d group_concat;
Table "ytt.group_concat"
Column | Type | Modifiers
----------+-----------------------+-----------
rank | integer |
username | character varying(20) |
表数据
t_girl=# select * from group_concat;
rank | username
------+----------
100 | Lucy
127 | Lucy
146 | Lucy
137 | Lucy
104 | Lucy
121 | Lucy
136 | Lily
100 | Lily
100 | Lily
105 | Lily
136 | Lily
149 | ytt
116 | ytt
116 | ytt
149 | ytt
106 | ytt
117 | ytt
(17 rows) Time: 0.638 ms
PostgreSQL 的rank 窗体函数演示样例:
t_girl=# select username,rank,rank() over(partition by username order by rank desc) as rank_cnt from group_concat;
username | rank | rank_cnt
----------+------+----------
Lily | 136 | 1
Lily | 136 | 1
Lily | 105 | 3
Lily | 100 | 4
Lily | 100 | 4
Lucy | 146 | 1
Lucy | 137 | 2
Lucy | 127 | 3
Lucy | 121 | 4
Lucy | 104 | 5
Lucy | 100 | 6
ytt | 149 | 1
ytt | 149 | 1
ytt | 117 | 3
ytt | 116 | 4
ytt | 116 | 4
ytt | 106 | 6
(17 rows) Time: 131.150 ms
MySQL 提供了group_concat 聚合函数能够变相的实现:
mysql>
select a.username, a.rank, find_in_set(a.rank,b.rank_gp) as rank_cnt
from group_concat as a ,
(select username,group_concat(rank order by rank desc separator ',') as rank_gp from group_concat group by username
) b
where a.username = b.username order by a.username asc,a.rank desc;
+----------+------+----------+
| username | rank | rank_cnt |
+----------+------+----------+
| Lily | 136 | 1 |
| Lily | 136 | 1 |
| Lily | 105 | 3 |
| Lily | 100 | 4 |
| Lily | 100 | 4 |
| Lucy | 146 | 1 |
| Lucy | 137 | 2 |
| Lucy | 127 | 3 |
| Lucy | 121 | 4 |
| Lucy | 104 | 5 |
| Lucy | 100 | 6 |
| ytt | 149 | 1 |
| ytt | 149 | 1 |
| ytt | 117 | 3 |
| ytt | 116 | 4 |
| ytt | 116 | 4 |
| ytt | 106 | 6 |
+----------+------+----------+
17 rows in set (0.02 sec)
当然了,假设MySQL SQL不太熟悉。能够用程序来处理,比方我以下用python 实现了rank 函数,运行结果例如以下:(脚本源码最后)
>>> ================================ RESTART ================================
>>>
username | rank | rank_cnt
--------------------------------
ytt |149 |1
ytt |149 |1
ytt |117 |3
ytt |116 |4
ytt |116 |4
ytt |106 |6
Lucy |146 |1
Lucy |137 |2
Lucy |127 |3
Lucy |121 |4
Lucy |104 |5
Lucy |100 |6
Lily |136 |1
Lily |136 |2
Lily |105 |3
Lily |100 |4
Lily |100 |4
(17 Rows.)
Time: 0.162 Seconds.
附上脚本代码:
from __future__ import print_function
from datetime import date, datetime, timedelta
import mysql.connector
import time
# Created by ytt 2014/5/14.
# Rank function implement.
def db_connect(is_true):
cnx = mysql.connector.connect(host='192.168.1.131',port='3306',user='python_user', password='python_user',database='t_girl',autocommit=is_true)
return cnx
def db_rs_rank(c1 ='username desc' ,c2 = ' rank desc'):
# c1: partition column.
# c2: sort column.
time_start = time.time()
cnx = db_connect(True)
rs = cnx.cursor()
query0 = "select username,rank from group_concat order by " + c1 + ", " + c2
rs.execute(query0,multi=False)
if rs.with_rows:
rows = rs.fetchall()
else:
return "No rows affected."
i = 0
j = 0
k = 1
result = []
field1_compare = rows[0][0]
field2_compare = rows[0][1]
while i < len(rows):
if field1_compare == rows[i][0]:
j += 1
if field2_compare != rows[i][1]:
field2_compare =rows[i][1]
k = j
result.append((rows[i][0],rows[i][1],k))
else:
j = 1
k = 1
field1_compare = rows[i][0]
result.append((rows[i][0],rows[i][1],k))
i += 1
i = 0
rows_header = list(rs.column_names)
rows_header.append('rank_cnt')
print (rows_header[0].center(10,' ') + '|' + rows_header[1].center(10,' ') + '|' + rows_header[2].center(10,' '))
print ('-'.center(32,'-'))
while i < len(result):
print (result[i][0].ljust(10,' ') + '|' + str(result[i][1]).ljust(10,' ') + '|' + str(result[i][2]).ljust(10,' '))
i += 1
rs.close()
cnx.close()
time_end = time.time()
print ('(' + str(len(rows))+ ' Rows.)')
print ("Time:" + str(round((time_end-time_start),3)).rjust(10,' ') + ' Seconds.')
if __name__=='__main__':
db_rs_rank()
MySQL 以及 Python 实现排名窗体函数的更多相关文章
- mysql及python交互
mysql在之前写过一次,那时是我刚刚进入博客,今天介绍一下mysql的python交互,当然前面会把mysql基本概述一下. 目录: 一.命令脚本(mysql) 1.基本命令 2.数据库操作命令 3 ...
- Mysql 查询实现成绩排名
Mysql 查询实现成绩排名,相同分数名次相同,类似于rank()函数 近日系统要实现总分成绩排名,而且相同分数的学生排名要一样,在网上搜了一圈,没有找到合适的方法,只能靠自己实现了,这里提供两种方法 ...
- Python基础(协程函数、内置函数、递归、模块和包)-day05
写在前面 上课第五天,打卡: 凭着爱,再回首: 一.协程函数(生成器:yield的表达式形式) 1.yield 的语句形式: yield 1 - 这种方式在 Python基础(函数部分)-day04 ...
- MySQL数据库之存储过程与存储函数
1 引言 存储过程和存储函数类似于面向对象程序设计语言中的方法,可以简化代码,提高代码的重用性.本文主要介绍如何创建存储过程和存储函数,以及存储过程与函数的使用.修改.删除等操作. 2 存储过程与存储 ...
- SQL Server Window Function 窗体函数读书笔记一 - SQL Windowing
SQL Server 窗体函数主要用来处理由 OVER 子句定义的行集, 主要用来分析和处理 Running totals Moving averages Gaps and islands 先看一个简 ...
- Python全栈 MySQL 数据库(SQL命令大全、MySQL 、Python调用)
为了梦想与了信仰 开局一张图 主要三个方面: 1.Linux终端命令 2.MySQL语句 3.Python调用 先删库 再跑路..... ...
- MySQL Connector/Python 接口 (一)
这里仅介绍 MySQL 官方开发的 Python 接口,参见这里: https://dev.mysql.com/doc/connector-python/en/ Chapter 1 Introduct ...
- 【简说Python WEB】视图函数操作数据库
目录 [简说Python WEB]视图函数操作数据库 系统环境:Ubuntu 18.04.1 LTS Python使用的是虚拟环境:virutalenv Python的版本:Python 3.6.9 ...
- 我的MYSQL学习心得(六) 函数
我的MYSQL学习心得(六) 函数 我的MYSQL学习心得(一) 简单语法 我的MYSQL学习心得(二) 数据类型宽度 我的MYSQL学习心得(三) 查看字段长度 我的MYSQL学习心得(四) 数据类 ...
随机推荐
- Python 绘图与可视化 matplotlib 散点图、numpy模块的random()
效果: 代码: def scatter_curve(): # plt.subplot(1,1,1) n=1024 X=np.random.normal(0,1,n) Y=np.random.norma ...
- 实现双向数据绑定mvvm
实现双向数据绑定mvvm
- win10开机时内存使用率达到99%以上
开始,运行,输入msconfig回车就能看到自启的项目. 搞定! 其实,感觉特别像是输入法的某个监听程序导致内存泄漏,造成的系统问题. 再遇到的时候要认真检查下.
- java的继承中构造方法
构造方法在创建对象的时候是被自动调用的,然后在继承中,是先调用父类的构造方法,然后在调用子类的构造方法, 当构造方法重写之后,在super中添加对应你想要调用构造方法的参数 例:父类 package ...
- 【BZOJ 1211】 [HNOI2004]树的计数
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] prufer数列的应用 http://www.cnblogs.com/AWCXV/p/7626625.html 这一题没有节点的度数 ...
- WinServer-IIS-IP及域的限制
如果启用域名限制,那么会对服务器产生比较大的资源开销,慎重选择这个 来自为知笔记(Wiz)
- POJ——T1789 Truck History
http://poj.org/problem?id=1789 Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 27597 ...
- java ee服务器/应用服务器的理解
42.由Apache.Sun 和其他一些公司及个人共同开发而成.由于有了Sun 的参与和支持,最新的Servlet 和JSP 规范总是能在Tomcat 中得到体现.43.可以这样认为,当在一台机器上配 ...
- SEO分享:关于SEO的十个问题
想写的幽默一点,幽默细胞太少,想写的专业一点,又不够专业,结果就出现了这篇不伦不类的怪文,望海涵! 导读:前面写过一篇类似的文章,受到的评价好坏都有吧.有人说讲的没有实质性的内容,有些人抱怨回答的太过 ...
- redis五种数据结构的指令
一.基本常用命令 select 选择数据库 0-15共16个库 keys 返回所有的键 keys mylist*代表取出所有mylist开头的键 exists 确认一个键存在不 del 删除 ...