The Programmer's Guide
  • About
  • Algorithm
    • Big O Notation
      • Tree
      • Problems
    • Basic Notes
    • Data Structure Implementation
      • Custom LinkedList
      • Custom Stack
      • Custom Queue
      • Custom Tree
        • Binary Tree Implementation
        • Binary Search Tree Implementation
        • Min Heap Implementation
        • Max Heap Implementation
        • Trie Implementation
      • Custom Graph
        • Adjacency List
        • Adjacency Matrix
        • Edge List
        • Bidirectional Search
    • Mathematical Algorithms
      • Problems - Set 1
      • Problems - Set 2
    • Bit Manipulation
      • Representation
      • Truth Tables
      • Number System
        • Java Program
      • Problems - Set 1
    • Searching
    • Sorting
    • Array Algorithms
    • String Algorithms
    • Tree
      • Tree Traversal Techniques
      • Tree Implementation
      • Applications of Trees
      • Problems - Set 1
    • Graph
      • Graph Traversal Techniques
      • Shortest Path Algorithms
      • Minimum Spanning Tree (MST) Algorithms
    • Dynamic Programming
      • Problems - Set 1
    • Recursion
    • Parallel Programming
    • Miscellaneous
      • Problems - Set 1
  • API
    • API Basics
      • What is an API?
      • Types of API
        • Comparison - TBU
      • Synchronous vs Asynchronous API
    • API Architecture
      • Synchronous & Asynchronous Communication
    • API Specification
  • Cloud Computing
    • Cloud Fundamentals
      • Cloud Terminology
      • Core Terminology
      • Cloud Models
      • Cloud Service Models
      • Benefits, Challenges and Risk of Cloud Computing
      • Cloud Ecosystem
  • Database
    • DBMS
      • Types of DBMS
        • Relational DBMS (RDBMS)
        • NoSQL DBMS
        • Object-Oriented DBMS (OODBMS)
        • Columnar DBMS
        • In-Memory DBMS
        • Distributed DBMS
        • Cloud-Based DBMS
        • Hierarchical DBMS
      • DBMS Architecture
      • DBMS Structure
    • SQL Databases
      • Terminology
      • RDBMS Concepts
        • Entity Relationship Diagram (ERD)
          • ERD Examples
        • Normalization
        • Denormalization
        • ACID & BASE Properties
          • ACID Properties
          • BASE Properties
        • Locking and Unlocking
      • SQL Fundamentals
        • SQL Commands
          • DDL (Data Definition Language)
          • DML (Data Manipulation Language)
          • DCL (Data Control Language)
          • TCL (Transaction Control Language)
          • DQL (Data Query Language)
        • SQL Operators
          • INTERSECT
          • EXCEPT
          • MINUS
          • IN and NOT IN
          • EXISTS and NOT EXISTS
        • SQL Clauses
          • Joins
          • OVER
          • WITH
          • CONNECT BY
          • MODEL
          • FETCH FIRST
          • KEEP
          • OFFSET with FETCH
        • SQL Functions
          • Oracle Specific
        • SQL Data Types
          • Numeric Types
          • Character Types
          • Date & Time Types
          • Large Object Types
        • Others
          • Indexing
      • Vendor Specific Concepts
        • Oracle Specific
          • Data Types
          • Character Set
          • Rownum, Rowid, Urowid
          • Order of Execution of the query
          • Keys
          • Tablespace
          • Partition
      • Best Practice
      • Resources & References
        • O’Reilly SQL Cookbook (2nd Edition)
          • 1. Retrieving Records
          • 2. Sorting Query Results
          • 3. Working with Multiple Tables
          • 4. Inserting, Updating, and Deleting
          • 5. Metadata Queries
          • 6. Working with Strings
          • 7. Working with Numbers
          • 8. Date Arithmetic
          • 9. Date Manipulation
          • 10. Working with Ranges
          • 11. Advanced Searching
          • 12. Reporting and Reshaping
          • 13. Hierarchical Queries
          • 14. Odds 'n' Ends
    • SQL vs NoSQL
    • Best Practices
  • Git
    • Commands
      • Setup and Configuration Commands
      • Getting and Creating Projects
      • Tracking Changes
      • Branching and Merging
      • Sharing and Updating Projects
      • Inspection and Comparison
      • Debugging
      • Patching
      • Stashing and Cleaning
      • Advanced Manipulations
    • Workflows
      • Branching Strategies
        • Git Flow
        • Trunk-Based Development
        • GitHub Flow
        • Comparison
      • Merge Strategies
        • Merge
        • Rebase
        • Squash
        • Fast-forward vs No-fast-forward
        • MR vs PR
      • Conflict Resolution
        • Handling Merge Conflicts
        • Merge Conflicts
        • Rebase Conflicts
        • Divergent Branches After git pull
        • Force Push
      • Patch & Recovery
        • Cherry-pick strategies
        • Revert vs Reset
        • Recover from a bad rebase
      • Rebasing Practices
        • Merge vs Rebase
        • Rebase develop branch on main branch
      • Repository Management
        • Working Directory
        • Mirror a repository
        • Convert a local folder to a Git repo
        • Backup and restore a Git repository
  • Java
    • Java Installation
    • Java Distributions
    • Java Platform Editions
      • Java SE
      • Java EE
      • Jakarta EE
      • Java ME
      • JavaFX
    • Java Overview
      • OOP Principles
        • Encapsulation
        • Inheritance
        • Polymorphism
        • Abstraction
          • Abstract Class & Method
          • Interface
            • Functional Interfaces
            • Marker Interfaces
          • Abstract Class vs Interface
      • OOP Basics
        • What is a Class?
          • Types of Classes
        • What is an Object?
          • Equals and HashCode
            • FAQ
          • Shallow Copy and Deep Copy
          • Ways to Create Object
          • Serialization & Deserialization
        • Methods & Fields
          • Method Overriding & Overloading
          • Method Signature & Header
          • Variables
        • Constructors
        • Access Modifiers
      • Parallelism & Concurrency
        • Ways to Identify Thread Concurrency or Parallelism
        • Thread Basics
          • Thread vs Process
          • Creating Threads
          • Thread Context Switching
          • Thread Lifecycle & States
          • Runnable & Callable
          • Types of Threads
          • Thread Priority
        • Thread Management & Synchronisation
          • Thread Resource Sharing
          • Thread Synchronization
            • Why is Synchronization Needed?
            • Synchronized Blocks & Methods
          • Thread Lock
            • Types of Locks
            • Intrinsic Lock (Monitor Lock)
            • Reentrant Lock
          • Semaphore
          • Thread Starvation
          • Thread Contention
          • Thread Deadlock
          • Best Practices for Avoiding Thread Issues
      • Keywords
        • this
        • super
        • Access Modifiers
      • Data Types
        • Default Values
        • Primitive Types
          • byte
          • short
          • int
          • long
          • float
          • double
          • char
          • boolean
        • Non-Primitive (Reference) Types
          • String
            • StringBuilder
            • StringBuffer
              • Problems
            • Multiline String
            • Comparison - String, StringBuilder & StringBuffer
          • Array
          • Collections
            • List
              • Array vs List
              • ArrayList
              • Vector
                • Stack
                  • Problems
              • LinkedList
            • Queue
              • PriorityQueue
              • Deque (Double-Ended Queue)
                • ArrayDeque
                • ConcurrentLinkedDeque - TBU
                • LinkedBlockingDeque - TBU
            • Map
              • HashMap
              • Hashtable
              • LinkedHashMap
              • ConcurrentHashMap
              • TreeMap
              • EnumMap
              • WeakHashMap
            • Set
              • HashSet
              • LinkedHashSet
              • TreeSet
              • EnumSet
              • ConcurrentSkipListSet
              • CopyOnWriteArraySet
        • Specialized Classes
          • BigInteger
          • BigDecimal
            • Examples
          • BitSet
          • Date and Time
            • Examples
          • Optional
          • Math
          • UUID
          • Scanner
          • Formatter
            • Examples
          • Properties
          • Regex (Pattern and Matcher)
            • Examples
          • Atomic Classes
          • Random
          • Format
            • NumberFormat
            • DateFormat
            • DecimalFormat
        • Others
          • Object
          • Enum
            • Pre-Defined Enum
            • Custom Enum
            • EnumSet and EnumMap
          • Record
          • Optional
          • System
          • Runtime
          • ProcessBuilder
          • Class
          • Void
          • Throwable
            • Error
            • Exception
              • Custom Exception Handling
              • Best Practice
            • Error vs Exception
            • StackTraceElement
    • Java Features by Version
      • How New Java Features are Released ?
      • Java Versions
        • Java 8
        • Java 9
        • Scoped Values
        • Unnamed Variables & Patterns
      • FAQ
    • Concepts
      • Set 1
        • Streams
          • flatmap
          • Collectors Utility Class
          • Problems
        • Functional Interfaces
          • Standard Built-In Interfaces
          • Custom Interfaces
        • Annotation
          • Custom Annotation
          • Meta Annotation
        • Generics
          • Covariance and Invariance
        • Asynchronous Computation
          • Future
          • CompletableFuture
          • Future v/s CompletableFuture
          • ExecutorService
            • Thread Pool
            • Types of Work Queues
            • Rejection Policies
            • ExecutorService Implementations
            • ExecutorService Usage
          • Locks, Atomic Variables, CountDownLatch, CyclicBarrier - TBU
          • Parallel Streams, Fork/Join Framework,Stream API with Parallelism - TBU
      • Set 2
        • Standards
          • ISO Standards
          • JSR
            • JSR 303, 349, 380 (Bean Validation)
        • Operator Precedence
      • Set 3
        • Date Time Formatter
        • Validation
      • Set 4
        • Input from User
        • Comparison & Ordering
          • Object Equality Check
          • Comparable and Comparator
            • Comparator Interface
          • Sorting of Objects
          • Insertion Ordering
    • Packages
      • Core Packages
        • java.lang
          • java.lang.System
          • java.lang.Thread
      • Jakarta Packages
        • jakarta.validation
        • javax.validation
      • Third-party Packages
    • Code Troubleshoot
      • Thread Dump
      • Heap Dump
    • Code Quality & Analysis
      • ArchUnit
      • Terminologies
        • Cyclic dependencies
    • Code Style
      • Naming Convention
      • Package Structure
      • Formatting
      • Comments and Documentation
      • Imports
      • Exception Handling
      • Class Structure
      • Method Guidelines
      • Page 1
      • Code Smells to Avoid
      • Lambdas and Streams Style
      • Tools
    • Tools
      • IntelliJ IDEA
        • Shortcuts for MAC
      • Apache JMeter
        • Examples
      • Thread Dump Capture
        • jstack
        • VisualVM - TBU
        • jcmd - TBU
        • JConsole - TBU
        • YourKit Java Profiler - TBU
        • Eclipse MAT - TBU
        • IntelliJ IDEA Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Thread Dump Analyzers - TBU
      • Heap Dump Capture
        • jmap
        • VisualVM - TBU
        • jcmd - TBU
        • Eclipse MAT (Memory Analyzer Tool) - TBU
        • IntelliJ IDEA Profiler - TBU
        • YourKit Java Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Kill -3 Command - TBU
        • jhat (Java Heap Analysis Tool) - TBU
        • JVM Options - TBU
      • Wireshark
        • Search Filters
    • Best Practices
      • Artifact and BOM Versioning
  • Maven
    • Installation
    • Local Repository & Configuration
    • Command-line Options
    • Build & Lifecycle
    • Dependency Management
      • Dependency
        • Transitive Dependency
        • Optional Dependency
      • Dependency Scope
        • Maven Lifecycle and Dependency Scope
      • Dependency Exclusions & Overrides
      • Bill of Materials (BOM)
      • Dependency Conflict Resolution
      • Dependency Tree & Analysis
      • Dependency Versioning Strategies
    • Plugins
      • Build Lifecycle Management
      • Dependency Management
      • Code Quality and Analysis
      • Documentation Generation
      • Code Generation
      • Packaging and Deployment
      • Reporting
      • Integration and Testing
      • Customization and Enhancement
        • build-helper-maven-plugin
        • properties-maven-plugin
        • ant-run plugin
        • exec-maven-plugin
        • gmavenplus-plugin
      • Performance Optimization
    • FAQs
      • Fixing Maven SSL Issues: Unable to Find Valid Certification Path
  • Spring
    • Spring Basics
      • What is Spring?
      • Why Use Spring
      • Spring Ecosystem
      • Versioning
      • Setting Up a Spring Project
    • Core Concepts
      • Spring Core
        • Dependency Injection (DI)
        • Stereotype Annotation
      • Spring Beans
        • Bean Lifecycle
        • Bean Scope
          • Singleton Bean
        • Lazy & Eager Initialization
          • Use Case of Lazy Initialization
        • BeanFactory
        • ApplicationContext
      • Spring Annotations
        • Spring Boot Specific
        • Controller Layer (Web & REST Controllers)
    • Spring Features
      • Auto Configuration
        • Spring Boot 2: spring.factories
        • Spring Boot 3: spring.factories
      • Spring Caching
        • In-Memory Caching
      • Spring AOP
        • Before Advice
        • After Returning Advice
        • After Throwing Advice
        • After (finally) Advice
        • Around Advice
      • Spring File Handling
      • Reactive Programming
        • Reactive System
        • Reactive Stream Specification
        • Project Reactor
          • Mono & Flux
      • Asynchronous Computation
        • @Async annotation
      • Spring Security
        • Authentication
          • Core Components
            • Security Filter Chain
              • HttpSecurity
              • Example
            • AuthenticationManager
            • AuthenticationProvider
            • UserDetailsService
              • UserDetails
              • PasswordEncoder
            • SecurityContext
            • SecurityContextHolder
            • GrantedAuthority
            • Security Configuration (Spring Security DSL)
          • Authentication Models
            • One-Way Authentication
            • Mutual Authentication
          • Authentication Mechanism
            • Basic Authentication
            • Form-Based Authentication
            • Token-Based Authentication (JWT)
            • OAuth2 Authentication
            • Multi-Factor Authentication (MFA)
            • SAML Authentication
            • X.509 Certificate Authentication
            • API Key Authentication
            • Remember-Me Authentication
            • Custom Authentication
          • Logout Handling
        • Authorization
        • Security Filters and Interceptors
        • CSRF
          • Real-World CSRF Attacks & Prevention
        • CORS
        • Session Management and Security
        • Best Practices
      • Spring Persistence
        • JDBC
          • JDBC Components
          • JDBC Template
          • Transaction Management
          • Best Practices in JDBC Usage
          • Datasource
            • Connection Pooling
              • HikariCP
            • Caching
        • JPA (Java Persistence API)
          • JPA Fundamentals
          • ORM Mapping Annotations
            • 1. Entity and Table Mappings
            • 2. Field/Column Mappings
            • 3. Relationship Mappings
            • 4. Inheritance Mappings
            • 5. Additional Configuration Annotations
          • Querying Data
            • JPQL
            • Criteria API
            • JPA Specification
              • Example - Employee Portal
            • Native SQL Queries
            • Named Queries
            • Query Return Types
            • Pagination & Sorting
              • Example - Employee Portal
            • Projection
          • Fetch Strategies in JPA
        • JPA Implementation
          • Hibernate
            • Properties
            • Example
        • Spring Data JPA
          • Repository Abstractions
          • Entity-to-Table Mapping
          • Derived Query Methods
        • Cross-Cutting Concerns
          • Transactions
          • Caching
          • Concurrency
        • Examples
          • Employee Portal
            • API
    • Distributed Systems & Communication
      • Distributed Scheduling
      • Inter-Service Communication
        • 1. RestTemplate
        • 2. WebClient
        • 3. OpenFeign
        • Retry Mechanism
          • @Retryable annotation
            • Example
    • Security & Data Protection
      • Encoding | Decoding
        • Types
          • Base Encoding
            • Base16 - TBD
              • Encoding and Decoding in Java - TBD
            • Base32
              • Encoding and Decoding in Java
            • Base64 -TBD
              • Encoding and Decoding in Java - TBD
          • Text Encoding - TBD
            • Extended ASCII
              • Encoding and Decoding in Java - TBD
                • ISO-8859-1
                • Windows-1252 - TBD
                • IBM Code Pages - TBD
            • ASCII
              • Encoding and Decoding in Java
        • Java Guidelines
          • Text Encoding Decoding Examples
          • Base Encoding Decoding Examples
          • Best Practices and Concepts
          • Libraries
      • Cryptography
        • Terminology
        • Java Cryptography Architecture (JCA)
        • Key Management
          • Key Generation
            • Tools and Libraries
              • OpenSSL
              • Java Keytool
                • Concept
                • Use Cases
            • Key & Certificate File Formats
          • Key Distribution
          • Key Storage
          • Key Rotation
          • Key Revocation
        • Encryption & Decryption
          • Symmetric Encryption
            • Algorithm
            • Modes of Operation
            • Examples
          • Asymmetric Encryption
            • Algorithm
            • Mode of Operation
            • Examples
    • Utilities & Libraries
      • Apache Libraries
        • Apache Camel
          • Camel Architecture
            • Camel Context
            • Camel Endpoints
            • Camel Components
            • Camel Exchange & MEP
          • Spring Dependency
          • Different Components
            • Camel SFTP
        • Apache Commons Lang
      • MapStruct Mapper
      • Utilities by Spring framework
        • FileCopyUtils
    • General Concepts
      • Spring Boot Artifact Packaging
      • Classpath and Resource Loading
      • Configuration - Mapping Properties to Java Class
      • Validations in Spring Framework
        • Jakarta Validation
          • Jakarta Bean Validation Annotations
    • Practical Guidelines
      • Spring Configuration
      • Spring Code Design
  • Software Testing
    • Software Testing Methodologies
      • Functional Testing
      • Non Functional Testing
    • Software Testing Life Cycle (STLC)
    • Integration Test
      • Dynamic Property Registration
    • Java Test Framework
      • JUnit
        • JUnit 4
          • Examples
        • JUnit 5
          • Examples
        • JUnit 4 vs JUnit 5
  • System Design
    • Low-Level Design (LLD)
      • Programming Paradigms
      • Design Pattern
        • Creational Pattern
        • Structural Pattern
        • Behavioral Pattern
        • Examples
          • Data Collector
          • Payment Processor
      • Object-Oriented Design
        • SOLID Principles
        • GRASP Principles
        • Composition
        • Aggregation
        • Association
      • Design Enhancements
        • Fluent API Design
          • Examples
    • High-Level Design (HLD)
      • CAP Theorem
      • Load Balancer
        • Load Balancer Architecture
        • Load Balancing in Java Microservices
          • Client-Side Load Balancing Example
          • Server-Side Load Balancing Example
        • Load Balancer Monitoring Tool
      • Architecture
        • Event Driven Architecture
          • Java Message Service (JMS)
          • Technologies & Frameworks
            • ActiveMQ
              • Architecture Details
              • Version Overview
              • Naming Convention
              • Message Delivery Guarantee
              • Queues and Topics
      • Scaling
        • Vertical Scaling (Scaling Up)
        • Horizontal Scaling (Scaling Out)
        • Auto-Scaling
        • Database Scaling via Sharding
      • Caching
        • Pod-Level vs Distributed Caching
      • Networking Metrics
        • Types of Delay
        • Scenario
      • System Characteristics
      • Workload Types
      • Resilience & Failure Handling
    • Performance
      • Why Is My API Sometimes Slow ?
    • Security
      • Security by Design
      • Zero Trust Security Model
      • Zero Trust Architecture
      • Principles
        • CIA
        • Least Privilege Principle
        • Defense in Depth
      • Security Threats & Mitigations
        • OWASP
          • Top 10 Security Threats
          • Application Security Verification Standard
          • Software Assurance Maturity Model
          • Dependency Check
          • CSRFGuard
          • Cheat Sheets
          • Security Testing Guide
          • Threat Dragon
        • Threat Modeling
      • Compliance & Regulation
        • PCI DSS
    • Deployment Patterns
    • Diagrams
      • UML Diagrams
        • PlantUML
          • Class Diagram
          • Object Diagram
          • Sequence Diagram
          • Use Case Diagram
          • Activity Diagram
          • State Diagram
          • Architecture Diagram
          • Component Diagram
          • Timing Diagram
          • ER Diagram (Entity-Relationship)
          • Network Diagram
    • Common Terminologies
    • Problems
      • Reference Materials
      • Cache Design
  • Interview Guide
    • Non-Technical
      • Behavioural or Introductory Guide
      • Project Specific
    • Technical
      • Java Interview Companion
        • Java Key Concepts
          • Set 1
          • Set 2
        • Java Code Snippets
        • Java Practice Programs
          • Set 3 - Strings
          • Set 4 - Search
          • Set 5 - Streams and Collection
      • SQL Interview Companion
        • SQL Practice Problems
          • Set 1
      • Spring Interview Companion
        • Spring Key Concepts
          • Set 1 - General
          • Set 2 - Core Spring
        • Spring Code Snippets
          • JPA
      • Application Server
      • Maven
      • Containerized Application
      • Microservices
    • General
      • Applicant Tracking System (ATS)
      • Flowchart - How to Solve Coding Problem?
Powered by GitBook
On this page
  • Pivoting a Result Set into One Row
  • Pivoting a Result Set into Multiple Rows
  • Reverse Pivoting a Result Set
  • Reverse Pivoting a Result Set into One Column
  • Suppressing Repeating Values from a Result Set
  • Pivoting a Result Set to Facilitate Inter-Row Calculations
  • Creating Buckets of Data, of a Fixed Size
  • Creating a Predefined Number of Buckets
  • Creating Vertical Histograms
  • Returning Non-GROUP BY Columns
  • Calculating Simple Subtotals
  • Calculating Subtotals for All Possible Expression Combinations
  • Identifying Rows That Are Not Subtotals
  • Using Case Expressions to Flag Rows
  • Creating a Sparse Matrix
  • Grouping Rows by Units of Time
  • Performing Aggregations over Different Groups/ Partitions Simultaneously
  • Performing Aggregations over a Moving Range of Values
  • Pivoting a Result Set with Subtotals

Was this helpful?

  1. Database
  2. SQL Databases
  3. Resources & References
  4. O’Reilly SQL Cookbook (2nd Edition)

12. Reporting and Reshaping

Previous11. Advanced SearchingNext13. Hierarchical Queries

Last updated 8 months ago

Was this helpful?

Pivoting a Result Set into One Row

We want to take values from groups of rows and turn those values into columns in a single row per group.

Sample Input

Sample Output

select 
    sum(case when deptno=10 then 1 else 0 end) as deptno_10,
    sum(case when deptno=20 then 1 else 0 end) as deptno_20,
    sum(case when deptno=30 then 1 else 0 end) as deptno_30
from emp

Pivoting a Result Set into Multiple Rows

We want to turn rows into columns by creating a column corresponding to each of the values in a single given column.

Sample Input

Sample Output

select 
    max(case when job='CLERK' then ename else null end) as clerks,
    max(case when job='ANALYST' then ename else null end) as analysts,
    max(case when job='MANAGER' then ename else null end) as mgrs,
    max(case when job='PRESIDENT' then ename else null end) as prez,
    max(case when job='SALESMAN' then ename else null end) as sales
from (
 select job,
 ename,
 row_number()over(partition by job order by ename) rn
 from emp
) x
group by rn

Explanation

Step 1:

select job,
ename,
row_number()over(partition by job order by ename) rn
from emp

Step 2:

select rn,
case when job='CLERK' then ename else null end as clerks,
case when job='ANALYST' then ename else null end as analysts,
case when job='MANAGER' then ename else null end as mgrs,
case when job='PRESIDENT' then ename else null end as prez,
case when job='SALESMAN' then ename else null end as sales
from (
select job,
ename,
row_number()over(partition by job order by ename) rn
from emp
) x

Note the blank spaces are null value. To remove the NULLs, use the aggregate function MAX or MIN and group by RN.

Reverse Pivoting a Result Set

We want to transform columns to rows.

Sample Input

Sample Output

select 
    dept.deptno,
    case dept.deptno
        when 10 then emp_cnts.deptno_10
        when 20 then emp_cnts.deptno_20
        when 30 then emp_cnts.deptno_30
        end as counts_by_dept
from emp_cnts cross join
(select deptno from dept where deptno <= 30) dept

Explanation

select * from EMP_CNTS;

There are three columns, and we need to create three rows. Begin by creating a Cartesian product between inline view EMP_CNTS and some table expression that has at least three rows. Following sample code uses table DEPT to create the Cartesian product. The Cartesian product enables you to return a row for each column in inline view EMP_CNTS.

select dept.deptno,
    emp_cnts.deptno_10,
    emp_cnts.deptno_20,
    emp_cnts.deptno_30
from (
    Select 
        sum(case when deptno=10 then 1 else 0 end) as deptno_10,
        sum(case when deptno=20 then 1 else 0 end) as deptno_20,
        sum(case when deptno=30 then 1 else 0 end) as deptno_30
    from emp
) emp_cnts,
(select deptno from dept where deptno <= 30) dept

Reverse Pivoting a Result Set into One Column

We want to return all columns from a query as just one column

Sample Output

Use the window function ROW_NUMBER OVER to rank each row based on EMPNO (1–4). Then use a CASE expression to transform three columns into one.

with four_rows (id)
as
(
    select 1
    union all
    select id+1
    from four_rows
    where id < 4
)
 ,
 x_tab (ename,job,sal,rn )
 as
 (
    select e.ename,e.job,e.sal,
     row_number()over(partition by e.empno order by e.empno)
     from emp e
     join four_rows on 1=1
 )

 select
 case rn
     when 1 then ename
     when 2 then job
     when 3 then cast(sal as char(4))
 end emps
 from x_tab

Explanation

Step 1: Use the window function ROW_NUMBER OVER to create a ranking for each employee in DEPTNO 10

Step 2: Add the Cartesian product

Step 3: Use a CASE expression to put ENAME, JOB, and SAL into one column for each employee

Suppressing Repeating Values from a Result Set

We are generating a report, and when two rows have the same value in a column, you want to display that value only once. For example below sample output.

select 
to_number( decode(lag(deptno)over(order by deptno), deptno,null,deptno) ) deptno, 
ename
from emp

Pivoting a Result Set to Facilitate Inter-Row Calculations

We want to make calculations involving data from multiple rows. For that, we want to pivot those rows into columns such that all values we need are then in a single row.

select d20_sal - d10_sal as d20_10_diff,
d20_sal - d30_sal as d20_30_diff
from (
    select sum(case when deptno=10 then sal end) as d10_sal,
    sum(case when deptno=20 then sal end) as d20_sal,
    sum(case when deptno=30 then sal end) as d30_sal
    from emp
) totals_by_dept

Creating Buckets of Data, of a Fixed Size

We want to organize data into evenly sized buckets, with a predetermined number of elements in each bucket. The total number of buckets may be unknown, but we want to ensure that each bucket has five elements.

Sample Output

GRP EMPNO ENAME
--- ---------- -------
1 7369 SMITH
1 7499 ALLEN
1 7521 WARD
1 7566 JONES
1 7654 MARTIN
2 7698 BLAKE
2 7782 CLARK
2 7788 SCOTT
2 7839 KING
2 7844 TURNER
3 7876 ADAMS
3 7900 JAMES
3 7902 FORD
3 7934 MILLER
select 
    ceil(row_number()over(order by empno)/5.0) grp,
    empno,
    ename
from emp

Creating a Predefined Number of Buckets

We want to organize the data into a fixed number of buckets. For example, we want to organize the employees in table EMP into four buckets.

Sample Output

NTILE organizes an ordered set into the number of buckets we specify, with any stragglers distributed into the available buckets starting from the first bucket

select ntile(4)over(order by empno) grp,
empno,
ename
from emp

We want to use SQL to generate histograms that extend horizontally. For example, see below output.

-- Oracle
select 
    deptno,
    lpad('*',count(*),'*') as cnt
from emp
group by deptno

Creating Vertical Histograms

We want to generate a histogram that grows from the bottom up. For example, below output.

select max(deptno_10) d10,
max(deptno_20) d20,
max(deptno_30) d30
from (
    select 
        row_number()over(partition by deptno order by empno) rn,
        case when deptno=10 then '*' else null end deptno_10,
        case when deptno=20 then '*' else null end deptno_20,
        case when deptno=30 then '*' else null end deptno_30
    from emp
) x
group by rn
order by 1 desc, 2 desc, 3 desc

Returning Non-GROUP BY Columns

We are executing a GROUP BY query, and want to return columns in the select list that are not also listed in GROUP BY clause. This is not usually possible, as such ungrouped columns would not represent a single value per row.

We want to find the employees who earn the highest and lowest salaries in each department, as well as the employees who earn the highest and lowest salaries in each job. Also, want to see each employee’s name, the department he works in, his job title, and his salary. Sample output below.

select deptno,
ename,
job,
sal,
case 
    when sal = max_by_dept then 'TOP SAL IN DEPT'
    when sal = min_by_dept then 'LOW SAL IN DEPT'
end dept_status,
case 
    when sal = max_by_job then 'TOP SAL IN JOB'
    when sal = min_by_job then 'LOW SAL IN JOB'
end job_status
from (
    select deptno,ename,job,sal,
    max(sal)over(partition by deptno) max_by_dept,
    max(sal)over(partition by job) max_by_job,
    min(sal)over(partition by deptno) min_by_dept,
    min(sal)over(partition by job) min_by_job
    from emp
) emp_sals
where sal in (max_by_dept,max_by_job,
min_by_dept,min_by_job)

Calculating Simple Subtotals

An example would be a result set that sums the salaries in table EMP by JOB and that also includes the sum of all salaries in table EMP.

A simple subtotal is defined as a result set that contains values from the aggregation of one column along with a grand total value for the table.

Calculating Subtotals for All Possible Expression Combinations

We want to find the sum of all salaries by DEPTNO, and by JOB, for every JOB/ DEPTNO combination.

Sample Output

DEPTNO JOB CATEGORY SAL
------ --------- --------------------- -------
10 CLERK TOTAL BY DEPT AND JOB 1300
10 MANAGER TOTAL BY DEPT AND JOB 2450
10 PRESIDENT TOTAL BY DEPT AND JOB 5000
20 CLERK TOTAL BY DEPT AND JOB 1900
30 CLERK TOTAL BY DEPT AND JOB 950
30 SALESMAN TOTAL BY DEPT AND JOB 5600
30 MANAGER TOTAL BY DEPT AND JOB 2850
20 MANAGER TOTAL BY DEPT AND JOB 2975
20 ANALYST TOTAL BY DEPT AND JOB 6000
    CLERK TOTAL BY JOB 4150
    ANALYST TOTAL BY JOB 6000
    MANAGER TOTAL BY JOB 8275
    PRESIDENT TOTAL BY JOB 5000
    SALESMAN TOTAL BY JOB 5600
10 TOTAL BY DEPT 8750
30 TOTAL BY DEPT 9400
20 TOTAL BY DEPT 10875
GRAND TOTAL FOR TABLE 29025
select 
   deptno,
   job,
   case grouping(deptno)||grouping(job)
      when '00' then 'TOTAL BY DEPT AND JOB'
      when '10' then 'TOTAL BY JOB'
      when '01' then 'TOTAL BY DEPT'
      when '11' then 'GRAND TOTALFOR TABLE'
   end category,
   sum(sal) sal
from emp
group by cube(deptno,job)
order by grouping(job),grouping(deptno)

Identifying Rows That Are Not Subtotals

We have used the CUBE extension of the GROUP BY clause to create a report, and need a way to differentiate between rows that would be generated by a normal GROUP BY clause and those rows that have been generated as a result of using CUBE or ROLLUP.

Sample Output

select deptno, job, sal,
    grouping(deptno) deptno_subtotals,
    grouping(job) job_subtotals
from emp
group by cube(deptno,job)

Using Case Expressions to Flag Rows

We want to return the following result set.

select ename,
    case when job = 'CLERK' then 1 else 0 end as is_clerk,
    case when job = 'SALESMAN' then 1 else 0 end as is_sales,
    case when job = 'MANAGER' then 1 else 0 end as is_mgr,
    case when job = 'ANALYST' then 1 else 0 end as is_analyst,
    case when job = 'PRESIDENT' then 1 else 0 end as is_prez
from emp
order by 2,3,4,5,6

Creating a Sparse Matrix

We want to create a sparse matrix, such as the following one transposing the DEPTNO and JOB columns of table EMP.

select 
    case deptno when 10 then ename end as d10,
    case deptno when 20 then ename end as d20,
    case deptno when 30 then ename end as d30,
    case job when 'CLERK' then ename end as clerks,
    case job when 'MANAGER' then ename end as mgrs,
    case job when 'PRESIDENT' then ename end as prez,
    case job when 'ANALYST' then ename end as anals,
    case job when 'SALESMAN' then ename end as sales
from emp

Grouping Rows by Units of Time

We want to summarize data by some interval of time. For example, we have a transaction log and want to summarize transactions by five-second intervals.

Sample Input

Sample Output

select 
    ceil(trx_id/5.0) as grp,
    min(trx_date) as trx_start,
    max(trx_date) as trx_end,
    sum(trx_cnt) as total
from trx_log
group by ceil(trx_id/5.0)

Performing Aggregations over Different Groups/ Partitions Simultaneously

We want to aggregate over different dimensions at the same time. For example, return a result set that lists each employee’s name, their department, the number of employees in their department (themselves included), the number of employees that have the same job (themselves included in this count as well), and the total number of employees in the EMP table.

select 
    ename,
    deptno,
    count(*) over(partition by deptno) deptno_cnt,
    job,
    count(*) over(partition by job) job_cnt,
    count(*) over() total
from emp

Performing Aggregations over a Moving Range of Values

We want to compute a moving aggregation, such as a moving sum on the salaries in table EMP. We want to compute a sum for every 90 days, starting with the HIREDATE of the first employee.

select hiredate,
sal,
sum(sal)over(order by hiredate range between 90 preceding and current row) spending_pattern
from emp e

Pivoting a Result Set with Subtotals

We want to create a report containing subtotals and then transpose the results to provide a more readable report.

Sample Output

select mgr,
    sum(case deptno when 10 then sal else 0 end) dept10,
    sum(case deptno when 20 then sal else 0 end) dept20,
    sum(case deptno when 30 then sal else 0 end) dept30,
    sum(case flag when '11' then sal else null end) total
from (
    select deptno,mgr,sum(sal) sal,
    cast(grouping(deptno) as char(1))||cast(grouping(mgr) as char(1)) flag
    from emp
    where mgr is not null
    group by rollup(deptno,mgr)
) x
group by mgr