1. 程式人生 > 資料庫 >python實現Oracle查詢分組的方法示例

python實現Oracle查詢分組的方法示例

本文例項講述了python實現Oracle查詢分組的方法。分享給大家供大家參考,具體如下:

1.分組的概念:

關鍵字:group by子句

結論:在select列表中如果出現了聚合函式,不是聚合函式的列,必須都要定義到group by子句的後面

需求:

查詢公司各個部門的平均工資?

select department_id,avg(salary)

from employees

group by department_id;

需求提升:

查詢公司各個部門不同工種的平均工資?

select department_id,job_id,avg(salary)

from employees

group by department_id,job_id;

2.having子句:

作用:用來過濾包含聚合函式的相關資訊(資料)

位置:

可以再group by前也可以再 group by後面(比較隨意)

需求:

查詢40、60、80號部門中平均工資大於6000的部門資訊?

以下程式碼實現有問題的:報錯了!!

報錯原因:如果需要對於聚合函式進行過濾不能使用where子句,

需要使用having子句來實現...

select department_id,avg(salary)

from employees

where avg(salary) > 6000 and department_id in(40,60,80)

group by department_id;

程式碼修改如下:

select department_id,avg(salary)

from employees

where department_id in(40,80)

having avg(salary) > 6000

group by department_id

order by department_id desc;

附:Python連線與查詢oracle資料庫示例:

import cx_Oracle
conn = cx_Oracle.connect('scott/tiger@localhost:1521/orcl')
cursor = conn.cursor()
cursor.execute("SELECT ENAME FROM EMP")
row = cursor.fetchone()
print row[0],cursor.close()
conn.close()


更多關於Python相關內容感興趣的讀者可檢視本站專題:《Python常見資料庫操作技巧彙總》、《Python編碼操作技巧總結》、《Python資料結構與演算法教程》、《Python Socket程式設計技巧總結》、《Python函式使用技巧總結》、《Python字串操作技巧彙總》、《Python入門與進階經典教程》及《Python檔案與目錄操作技巧彙總》

希望本文所述對大家Python程式設計有所幫助。