Databázové systémy. SQL Window functions

Similar documents
Poradové a agregačné window funkcie. ROLLUP a CUBE

The Plan. What will we cover? - Review Some Basics - Set Operators - Subqueries - Aggregate Filter Clause - Window Functions Galore - CTE s - Lateral

Postgres Window Magic

Spájanie tabuliek. Jaroslav Porubän, Miroslav Biňas, Milan Nosáľ (c)

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables

Joining tables. Jaroslav Porubän, Miroslav Biňas, Milan Nosáľ (c)

Set theory is a branch of mathematics that studies sets. Sets are a collection of objects.

Intermediate SQL: Aggregated Data, Joins and Set Operators

Database Management Systems,

FUN WITH ANALYTIC FUNCTIONS UTOUG TRAINING DAYS 2017

Retrieving Data Using the SQL SELECT Statement. Copyright 2004, Oracle. All rights reserved.

Restricting and Sorting Data. Copyright 2004, Oracle. All rights reserved.

MySQL 8.0 Common Table Expressions & Windowing Functions

SQL Recursion, Window Queries

Copyright 2017, Oracle and/or its aff iliates. All rights reserved.

Join, Sub queries and set operators

KORA. RDBMS Concepts II

Data Manipulation Language (DML)

Structure Query Language (SQL)

Based on the following Table(s), Write down the queries as indicated: 1. Write an SQL query to insert a new row in table Dept with values: 4, Prog, MO

Databázy (1) Prednáška 11. Alexander Šimko

Chapter 6 Windowed Tables and Window Functions in SQL

Retrieving Data Using the SQL SELECT Statement. Copyright 2004, Oracle. All rights reserved.

This lecture. Databases - SQL II. Counting students. Summary Functions

Databases - SQL II. (GF Royle, N Spadaccini ) Structured Query Language II 1 / 22

Creating Other Schema Objects

Rows and Range, Preceding and Following

Databázy (1) Prednáška 08. Alexander Šimko

RETRIEVING DATA USING THE SQL SELECT STATEMENT

SQL. Char (30) can store ram, ramji007 or 80- b

CSEN 501 CSEN501 - Databases I

Retrieving Data from Multiple Tables

MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9)

Fundamentals of Database Systems

SQL Queries. COSC 304 Introduction to Database Systems SQL. Example Relations. SQL and Relational Algebra. Example Relation Instances

Note that it works well to answer questions on computer instead of on the board.

Retrieving Data Using the SQL SELECT Statement. Copyright 2009, Oracle. All rights reserved.

Chapter 9 Windowed Tables and Window Functions in SQL. Recent Development for Data Models 2016 Stefan Deßloch

1Z0-007 ineroduction to oracle9l:sql

Restricting and Sorting Data. Copyright 2004, Oracle. All rights reserved.

Advance Database Systems. Joining Concepts in Advanced SQL Lecture# 4

GIFT Department of Computing Science. CS-217/224: Database Systems. Lab-5 Manual. Displaying Data from Multiple Tables - SQL Joins

COSC 304 Introduction to Database Systems SQL. Dr. Ramon Lawrence University of British Columbia Okanagan

CSC Web Programming. Introduction to SQL

What Are Group Functions? Reporting Aggregated Data Using the Group Functions. Objectives. Types of Group Functions

Introduction to Oracle9i: SQL

GIFT Department of Computing Science Data Selection and Filtering using the SELECT Statement

COMP7640 Assignment 2

Database Programming with SQL

Chapter 6 Windowed Tables and Window Functions in SQL

Chapter 6 Windowed Tables and Window Functions in SQL

20461: Querying Microsoft SQL Server 2014 Databases

Oracle Database SQL Basics

NESTED QUERIES AND AGGREGATION CHAPTER 5 (6/E) CHAPTER 8 (5/E)

SQL Server Windowing Functions

Aggregate Functions. Eng. Mohammed Alokshiya. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Dept. Database Lab (ECOM 4113)

Why Relational Databases? Relational databases allow for the storage and analysis of large amounts of data.

Database Management Systems,

COURSE OUTLINE MOC 20461: QUERYING MICROSOFT SQL SERVER 2014

Database Programming with SQL

COMP 244 DATABASE CONCEPTS & APPLICATIONS

Implementing Table Operations Using Structured Query Language (SQL) Using Multiple Operations. SQL: Structured Query Language

Database Foundations. 6-9 Joining Tables Using JOIN. Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Introduction. Sample Database SQL-92. Sample Data. Sample Data. Chapter 6 Introduction to Structured Query Language (SQL)

Unit 1 - Chapter 4,5

SQL Data Query Language

ASSIGNMENT NO Computer System with Open Source Operating System. 2. Mysql

Reporting Aggregated Data Using the Group Functions. Copyright 2004, Oracle. All rights reserved.

SQL Data Manipulation Language. Lecture 5. Introduction to SQL language. Last updated: December 10, 2014

Database Technology. Topic 3: SQL. Olaf Hartig.

EXISTS NOT EXISTS WITH

Table Joins and Indexes in SQL

1Z Oracle Database 11g - SQL Fundamentals I Exam Summary Syllabus Questions

DUE: 9. Create a query that will return the average order total for all Global Fast Foods orders from January 1, 2002, to December 21, 2002.

NESTED QUERIES AND AGGREGATION CHAPTER 5 (6/E) CHAPTER 8 (5/E)

Introduction to Oracle9i: SQL

20461: Querying Microsoft SQL Server

AVANTUS TRAINING PTE LTD

Querying Microsoft SQL Server (MOC 20461C)

In This Lecture. Yet More SQL SELECT ORDER BY. SQL SELECT Overview. ORDER BY Example. ORDER BY Example. Yet more SQL

Chapter 9: Working With Data

After completing this course, participants will be able to:

COUNT Function. The COUNT function returns the number of rows in a query.

The Amazing Utility. of ROW_NUMBER() Brian

Querying Microsoft SQL Server

SQL Server 2012 Development Course

Querying Microsoft SQL Server

Querying Microsoft SQL Server 2008/2012

COURSE OUTLINE: Querying Microsoft SQL Server

RESTRICTING AND SORTING DATA

Subquery: There are basically three types of subqueries are:

CS 338 Basic SQL Part II

Displaying Data from Multiple Tables. Copyright 2004, Oracle. All rights reserved.

Real-World Performance Training SQL Introduction

CS2 Current Technologies Lecture 2: SQL Programming Basics

SQL Structured Query Language Introduction

Institute of Aga. Network Database LECTURER NIYAZ M. SALIH

Constraint satisfaction problems (problémy s obmedzujúcimi podmienkami)

Structured Query Language Continued. Rose-Hulman Institute of Technology Curt Clifton

Objectives. After completing this lesson, you should be able to do the following:

Transcription:

Databázové systémy SQL Window functions

Scores Tabuľka s bodmi pre jednotlivých študentov id, name, score Chceme ku každému doplniť rozdiel voči priemeru 2

Demo data SELECT * FROM scores ORDER BY score DESC; 3

Obvious riešenie SELECT s.name, s.score, s.score - (SELECT avg(score) FROM scores) FROM scores s ORDER BY 2 DESC; 4

Riešenie cez Window Functions SELECT s.name, s.score, s.score - avg(score) OVER () FROM scores s ORDER BY 2 DESC; 5

Scores 2 Tabuľka s bodmi pre jednotlivých študentov id, name, study_programme, score Chceme ich zoradiť a ku každému dopísať jeho poradie Ak majú dvaja rovnaký počet bodov, tak nech majú rovnakú pozíciu 6

Riešenie so subselect SELECT s1.name, s1.score as score, ( SELECT count(distinct s2.score) FROM scores s2 WHERE s2.score >= s1.score ) AS rank FROM scores s1 ORDER BY 2 DESC, 1 7

Riešenie cez Window Functions SELECT s.name, s.score, DENSE_RANK() OVER (ORDER BY s.score DESC) FROM scores s ORDER BY 2 DESC,1 8

A chceme to po študijných programoch SELECT s.name, s.study_programme, s.score, DENSE_RANK() OVER (PARTITION BY stu dy_programme ORDER BY score DESC) FROM scores s ORDER BY 2, 3 DESC,1 9

Príklad employees Napíšte SELECT, ktorý vráti zamestnancov, ktorý poberajú tri najvyššie platy v každom oddelení. Ak poberá jeden z troch top platov oddelenia viacero zamestnancov, nech sú vo výpise všetci. Výpis nech obsahuje (v tomto poradí) názov oddelenia, meno zamestnanca a jeho plat a nech je zoradený podľa mena oddelenia vzostupne, výšky platu zostupne a mena zamestnanca vzostupne. 10

Riešenie... SELECT d.name as department, e3.name as employee, e3.salary FROM employees e3 JOIN (SELECT DISTINCT e.department_id, e.salary FROM employees e WHERE (SELECT COUNT(*) FROM (SELECT DISTINCT department_id, salary FROM employees) e2 WHERE e2.department_id = e.department_id AND e2.salary > e.salary) < 3) tmp ON tmp.department_id = e3.department_id AND tmp.salary = e3.salary JOIN departments d ON e3.department_id = d.id ORDER BY 1, 3 DESC, 2 ASC 11

Riešenie... SELECT d.name as department, e3.name as employee, e3.salary FROM employees e3 JOIN (SELECT DISTINCT e.department_id, e.salary FROM employees e WHERE (SELECT COUNT(*) FROM (SELECT DISTINCT department_id, salary FROM employees) e2 WHERE e2.department_id = e.department_id AND e2.salary > e.salary) < 3) tmp ON tmp.department_id = e3.department_id AND tmp.salary = e3.salary JOIN departments d ON e3.department_id = d.id ORDER BY 1, 3 DESC, 2 ASC 12

Riešenie... JOIN( SELECT DISTINCT e.department_id, e.salary FROM employees e WHERE ( SELECT COUNT(*) FROM (SELECT DISTINCT department_id, salary FROM employees) e2 WHERE e2.department_id = e.department_id AND e2.salary > e.salary) < 3 ) tmp ON tmp.department_id = e3.department_id AND tmp.salary = e3.salary 13

Riešenie... SELECT DISTINCT e.department_id, e.salary FROM employees e WHERE ( SELECT COUNT(*) FROM ( SELECT DISTINCT department_id, salary FROM employees) e2 WHERE e2.department_id = e.department_id AND e2.salary > e.salary) < 3) 14

Existuje aj riešenie pomocou ORDER BY + DISTINCT ON komba 15

Employees pomocou window functions SELECT tmp.name, tmp.empl, tmp.salary FROM ( SELECT d.name, e.name empl, e.salary, DENSE_RANK() OVER (PARTITION BY d.id ORDER BY e.salary DESC) as rank FROM departments d JOIN employees e ON e.department_id = d.id ) tmp WHERE tmp.rank < 4 ORDER BY 1,3 DESC, 2 ASC; 16

Window functions Výpočet nad sadou riadkov, ktoré súvisia s aktuálnym riadkom Agregácia, ktorá vám nezruší spracovanie po riadkoch, neurobí GROUP BY do jednej hodnoty Viete si určiť okno (partíciu) a frame okolo aktuálneho riadku A zistiť napr. pozíciu aktuálneho riadku v okne 17

Syntax function_name ([expression [, expression... ]]) [ FILTER ( WHERE filter_clause ) ] OVER ( window_definition ) http://www.postgresql.org/docs/current/static/sql -expressions.html#syntax-window-functi ONS 18

Syntax function_name ([expression [, expression... ]]) [ FILTER ( WHERE filter_clause ) ] OVER ( window_definition ) http://www.postgresql.org/docs/current/static/sqlexpressions.html#syntax-window-functions 19

Window definition [ existing_window_name ] [ PARTITION BY expression [,...] ] [ ORDER BY expression [ ASC DESC USING operator ] [ NULLS { FIRST LAST } ] [,...] ] [ frame_clause ] http://www.postgresql.org/docs/current/static/sqlexpressions.html#syntax-window-functions 20

Frame clause { RANGE ROWS } frame_start { RANGE ROWS } BETWEEN frame_start AND frame_end frame_start a frame_end: UNBOUNDED PRECEDING value PRECEDING CURRENT ROW value FOLLOWING UNBOUNDED FOLLOWING 21

Default frame The default framing option is RANGE UNBOUNDED PRECEDING, which is the same as RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. With ORDER BY, this sets the frame to be all rows from the partition start up through the current row's last ORDER BY peer. Without ORDER BY, all rows of the partition are included in the window frame, since all rows become peers of the current row. 22

Default frame The default framing option is RANGE UNBOUNDED PRECEDING, which is the same as RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. With ORDER BY, this sets the frame to be all rows from the partition start up through the current row's last ORDER BY peer. Without ORDER BY, all rows of the partition are included in the window frame, since all rows become peers of the current row. 23

expressions Ľubovoľná agregácia alebo Window function podľa http://www.postgresql.org/docs/current/static/fu nctions-window.html 24

Demo 25

Zhrnutie Window functions nám dávajú kontext práve spracovaného riadka Running sums, ranking.. Často sa dá problém vyriešiť aj bez nich Ale s nimi to môže byť efektívnejšie, elegantnejšie, čitatelnejšie 26