100% found this document useful (3 votes)
25 views

Full download SQL Server Analytical Toolkit: Using Windowing, Analytical, Ranking, and Aggregate Functions for Data and Statistical Analysis 1st Edition Angelo Bobak pdf docx

Angelo

Uploaded by

qillahmyrnes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
25 views

Full download SQL Server Analytical Toolkit: Using Windowing, Analytical, Ranking, and Aggregate Functions for Data and Statistical Analysis 1st Edition Angelo Bobak pdf docx

Angelo

Uploaded by

qillahmyrnes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Download the full version of the ebook at

https://ebookmass.com

SQL Server Analytical Toolkit: Using


Windowing, Analytical, Ranking, and Aggregate
Functions for Data and Statistical Analysis
1st Edition Angelo Bobak
https://ebookmass.com/product/sql-server-
analytical-toolkit-using-windowing-analytical-
ranking-and-aggregate-functions-for-data-and-
statistical-analysis-1st-edition-angelo-bobak/

Explore and download more ebook at https://ebookmass.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Practical Graph Structures in SQL Server and Azure SQL:


Enabling Deeper Insights Using Highly Connected Data 1st
Edition Louis Davidson
https://ebookmass.com/product/practical-graph-structures-in-sql-
server-and-azure-sql-enabling-deeper-insights-using-highly-connected-
data-1st-edition-louis-davidson-2/
testbankdeal.com

Practical Graph Structures in SQL Server and Azure SQL:


Enabling Deeper Insights Using Highly Connected Data 1st
Edition Louis Davidson
https://ebookmass.com/product/practical-graph-structures-in-sql-
server-and-azure-sql-enabling-deeper-insights-using-highly-connected-
data-1st-edition-louis-davidson/
testbankdeal.com

Fixed Income Mathematics: Analytical and Statistical


Techniques, 5th Edition Frank J. Fabozzi

https://ebookmass.com/product/fixed-income-mathematics-analytical-and-
statistical-techniques-5th-edition-frank-j-fabozzi/

testbankdeal.com

Applied Analysis of Composite Media: Analytical and


Computational Approaches Dryga■

https://ebookmass.com/product/applied-analysis-of-composite-media-
analytical-and-computational-approaches-drygas/

testbankdeal.com
Paper-Based Analytical Devices for Chemical Analysis and
Diagnostics William R. De Araujo

https://ebookmass.com/product/paper-based-analytical-devices-for-
chemical-analysis-and-diagnostics-william-r-de-araujo/

testbankdeal.com

Applied Analysis of Composite Media: Analytical and


Computational Approaches Piotr Drygas

https://ebookmass.com/product/applied-analysis-of-composite-media-
analytical-and-computational-approaches-piotr-drygas/

testbankdeal.com

Statistical Methods for Survival Data Analysis 3rd Edition


Lee

https://ebookmass.com/product/statistical-methods-for-survival-data-
analysis-3rd-edition-lee/

testbankdeal.com

Carbon Dots in Analytical Chemistry: Detection and Imaging


Suresh Kumar Kailasa

https://ebookmass.com/product/carbon-dots-in-analytical-chemistry-
detection-and-imaging-suresh-kumar-kailasa/

testbankdeal.com

Numerical Methods Using Kotlin: For Data Science,


Analysis, and Engineering 1st Edition Haksun Li

https://ebookmass.com/product/numerical-methods-using-kotlin-for-data-
science-analysis-and-engineering-1st-edition-haksun-li-2/

testbankdeal.com
SQL Server
Analytical
Toolkit
Using Windowing, Analytical, Ranking,
and Aggregate Functions for Data and
Statistical Analysis

Angelo Bobak
SQL Server Analytical
Toolkit
Using Windowing, Analytical,
Ranking, and Aggregate Functions
for Data and Statistical Analysis

Angelo Bobak
SQL Server Analytical Toolkit: Using Windowing, Analytical, Ranking, and Aggregate
Functions for Data and Statistical Analysis
Angelo Bobak
Hastings On Hudson, NY, USA

ISBN-13 (pbk): 978-1-4842-8666-1 ISBN-13 (electronic): 978-1-4842-8667-8


https://doi.org/10.1007/978-1-4842-8667-8

Copyright © 2023 by Angelo Bobak


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Joan Murray
Development Editor: Laura Berendson
Coordinating Editor: Gryffin Winkler
Cover image designed by Freepik (www.freepik.com)
Distributed to the book trade worldwide by Springer Science+Business Media LLC, 1 New York Plaza,
Suite 4600, New York, NY 10004. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-
sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member
(owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a
Delaware corporation.
For information on translations, please e-mail [email protected]; for reprint,
paperback, or audio rights, please e-mail [email protected].
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub.
Paper in this product is recyclable
I would like to dedicate this book to my wife, Cathy, for all her support
and patience throughout my career and all my book projects. I would
like to thank Apress for this opportunity, specifically Joan Murray, the
acquisition editor, who gave me this chance and Laura Berendson
and Gryffin Winkler for their valuable help and suggestions.
Last but not least, I thank all the technical reviewers for their
suggestions, tips, and corrections. What’s good about this book is
because of them. What’s not so good is entirely due to me!
Table of Contents
About the Author�����������������������������������������������������������������������������������������������������xv

About the Technical Reviewer�������������������������������������������������������������������������������xvii


Introduction������������������������������������������������������������������������������������������������������������xix

Chapter 1: Partitions, Frames, and the OVER( ) Clause��������������������������������������������� 1


What Are Partitions and Window Frames?������������������������������������������������������������������������������������ 1
What Is an OVER( ) Clause?����������������������������������������������������������������������������������������������������������� 2
History of the OVER( ) Clause and Window Functions������������������������������������������������������������������� 2
The Window Functions������������������������������������������������������������������������������������������������������������������ 3
The OVER( ) Clause������������������������������������������������������������������������������������������������������������������������ 4
Syntax������������������������������������������������������������������������������������������������������������������������������������������� 4
Partitions and Frames������������������������������������������������������������������������������������������������������������������� 6
ROWS Frame Definition����������������������������������������������������������������������������������������������������������������� 8
RANGE Frame Definition������������������������������������������������������������������������������������������������������������� 16
Example 1����������������������������������������������������������������������������������������������������������������������������������� 19
ROWS and RANGE Default Behavior�������������������������������������������������������������������������������������������� 23
Scenario 1����������������������������������������������������������������������������������������������������������������������������� 24
Scenario 2����������������������������������������������������������������������������������������������������������������������������� 24
ROWS and RANGE Window Frame Examples������������������������������������������������������������������������������ 25
Data Set��������������������������������������������������������������������������������������������������������������������������������� 25
Example 2������������������������������������������������������������������������������������������������������������������������������ 29
Example 3������������������������������������������������������������������������������������������������������������������������������ 32
Example 4������������������������������������������������������������������������������������������������������������������������������ 34
Example 5������������������������������������������������������������������������������������������������������������������������������ 38
Summary������������������������������������������������������������������������������������������������������������������������������������ 40

v
Table of Contents

Chapter 2: Sales DW Use Case: Aggregate Functions��������������������������������������������� 43


Sales Data Warehouse���������������������������������������������������������������������������������������������������������������� 43
Sales Data Warehouse Conceptual Model����������������������������������������������������������������������������������� 45
A Word About Performance Tuning���������������������������������������������������������������������������������������������� 50
Aggregate Functions������������������������������������������������������������������������������������������������������������������� 60
COUNT( ), MAX( ), MIN( ), AVG( ), and SUM( ) Functions����������������������������������������������������������� 61
With OVER( )��������������������������������������������������������������������������������������������������������������������������� 63
GROUPING( ) Function������������������������������������������������������������������������������������������������������������ 67
GROUPING: Performance Tuning Considerations������������������������������������������������������������������� 71
STRING_AGG Function����������������������������������������������������������������������������������������������������������� 77
STDEV( ) and STDEVP( ) Functions����������������������������������������������������������������������������������������� 80
STDEV: Performance Tuning Considerations�������������������������������������������������������������������������� 85
VAR( ) and VARP( ) Functions�������������������������������������������������������������������������������������������������� 91
SQL Server 2022: Named Window Example�������������������������������������������������������������������������������� 95
Summary���������������������������������������������������������������������������������������������������������������������������������� 103

Chapter 3: Sales Use Case: Analytical Functions������������������������������������������������� 105


Analytical Functions������������������������������������������������������������������������������������������������������������������ 105
CUME_DIST( ) Function�������������������������������������������������������������������������������������������������������� 106
Performance Considerations����������������������������������������������������������������������������������������������� 112
PERCENT_RANK( ) Function������������������������������������������������������������������������������������������������� 117
Performance Considerations����������������������������������������������������������������������������������������������� 124
High-Performance Strategy������������������������������������������������������������������������������������������������� 127
LAST_VALUE( ) and FIRST_VALUE( )������������������������������������������������������������������������������������� 134
Performance Considerations����������������������������������������������������������������������������������������������� 137
LAG( ) and LEAD( )���������������������������������������������������������������������������������������������������������������� 140
Performance Considerations����������������������������������������������������������������������������������������������� 142
PERCENTILE_CONT( ) and PERCENTILE_DISC( )������������������������������������������������������������������� 147
Performance Considerations����������������������������������������������������������������������������������������������� 152
Using a Report Table������������������������������������������������������������������������������������������������������������ 157
Summary���������������������������������������������������������������������������������������������������������������������������������� 163

vi
Table of Contents

Chapter 4: Sales Use Case: Ranking/Window Functions�������������������������������������� 165


Ranking/Window Functions������������������������������������������������������������������������������������������������������ 165
RANK( ) vs. PERCENT_RANK( )��������������������������������������������������������������������������������������������� 171
Performance Considerations����������������������������������������������������������������������������������������������� 175
RANK( ) vs. DENSE_RANK( )������������������������������������������������������������������������������������������������� 179
Performance Considerations����������������������������������������������������������������������������������������������� 183
NTILE( ) Function Revisited�������������������������������������������������������������������������������������������������� 185
Performance Considerations����������������������������������������������������������������������������������������������� 188
ROW_NUMBER( ) Function��������������������������������������������������������������������������������������������������� 190
Performance Considerations����������������������������������������������������������������������������������������������� 194
Islands and Gaps Example��������������������������������������������������������������������������������������������������� 201
Summary���������������������������������������������������������������������������������������������������������������������������������� 209

Chapter 5: Finance Use Case: Aggregate Functions��������������������������������������������� 211


Aggregate Functions����������������������������������������������������������������������������������������������������������������� 211
COUNT( ) and SUM( ) Functions�������������������������������������������������������������������������������������������� 217
Performance Considerations����������������������������������������������������������������������������������������������� 226
SUM( ) Function������������������������������������������������������������������������������������������������������������������� 234
Performance Considerations����������������������������������������������������������������������������������������������� 238
MIN( ) and MAX( ) Functions������������������������������������������������������������������������������������������������� 244
Performance Considerations����������������������������������������������������������������������������������������������� 250
AVG( ) Function�������������������������������������������������������������������������������������������������������������������� 258
Performance Considerations����������������������������������������������������������������������������������������������� 264
GROUPING Function������������������������������������������������������������������������������������������������������������� 267
Performance Considerations����������������������������������������������������������������������������������������������� 272
STRING_AGG( ) Function������������������������������������������������������������������������������������������������������ 277
STDEV( ) and STDEVP( ) Functions��������������������������������������������������������������������������������������� 278
Performance Considerations����������������������������������������������������������������������������������������������� 286
VAR( ) and VARP( ) Functions������������������������������������������������������������������������������������������������ 297
Ticker Analysis�������������������������������������������������������������������������������������������������������������������������� 302

vii
Table of Contents

More Non-statistical Variance��������������������������������������������������������������������������������������������� 305


Even More Statistical Variance�������������������������������������������������������������������������������������������� 308
Summary���������������������������������������������������������������������������������������������������������������������������������� 311

Chapter 6: Finance Use Case: Ranking Functions������������������������������������������������ 313


Ranking Functions�������������������������������������������������������������������������������������������������������������������� 313
RANK( ) Function������������������������������������������������������������������������������������������������������������������ 314
DENSE_RANK( ) Function����������������������������������������������������������������������������������������������������� 341
NTILE( ) Function������������������������������������������������������������������������������������������������������������������ 355
ROW_NUMBER( ) Function��������������������������������������������������������������������������������������������������� 370
The Data Gaps and Islands Problem����������������������������������������������������������������������������������������� 377
Step 1: Create the First CTE������������������������������������������������������������������������������������������������� 383
Step 2: Set Up the Second CTE to Label Gaps��������������������������������������������������������������������� 386
Step 3: Set Up the Third CTE and Identify Start/Stop Dates of Gaps����������������������������������� 388
Step 4: Generate the Report������������������������������������������������������������������������������������������������ 390
Performance Considerations����������������������������������������������������������������������������������������������� 392
Islands Next������������������������������������������������������������������������������������������������������������������������������ 395
Step 1: Create the First CTE Using LAG( ) and LEAD( )��������������������������������������������������������� 395
Step 2: Create the Second CTE That Labels Islands and Gaps�������������������������������������������� 397
Step 3: Identify Island Start/Stop Dates������������������������������������������������������������������������������� 402
Step 4: Create the Final Report�������������������������������������������������������������������������������������������� 404
Summary���������������������������������������������������������������������������������������������������������������������������������� 408

Chapter 7: Finance Use Case: Analytical Functions���������������������������������������������� 409


Analytical Functions������������������������������������������������������������������������������������������������������������������ 409
CUME_DIST( ) Function�������������������������������������������������������������������������������������������������������� 410
Performance Considerations����������������������������������������������������������������������������������������������� 416
FIRST_VALUE( ) and LAST_VALUE( ) Functions��������������������������������������������������������������������� 420
Performance Considerations����������������������������������������������������������������������������������������������� 424
LAG( ) and LEAD( ) Functions������������������������������������������������������������������������������������������������ 431
LAG( ) Function��������������������������������������������������������������������������������������������������������������������� 431
Performance Considerations����������������������������������������������������������������������������������������������� 435
LEAD( ) Function������������������������������������������������������������������������������������������������������������������ 440

viii
Table of Contents

Performance Considerations����������������������������������������������������������������������������������������������� 442


Memory-Optimized Strategy����������������������������������������������������������������������������������������������� 445
PERCENT_RANK( ) Function������������������������������������������������������������������������������������������������� 450
Performance Considerations����������������������������������������������������������������������������������������������� 453
PERCENTILE_CONT( ) and PERCENTILE_DISC( )������������������������������������������������������������������� 455
PERCENTILE_CONT( )����������������������������������������������������������������������������������������������������������� 455
Performance Considerations����������������������������������������������������������������������������������������������� 459
PERCENTILE_DISC Function������������������������������������������������������������������������������������������������ 462
Performance Considerations����������������������������������������������������������������������������������������������� 465
Multi-memory-enhanced-table Strategy����������������������������������������������������������������������������� 471
Performance Considerations����������������������������������������������������������������������������������������������� 476
Summary���������������������������������������������������������������������������������������������������������������������������������� 482

Chapter 8: Plant Use Case: Aggregate Functions������������������������������������������������� 483


Aggregate Functions����������������������������������������������������������������������������������������������������������������� 484
Data Model�������������������������������������������������������������������������������������������������������������������������������� 485
Data Dictionaries����������������������������������������������������������������������������������������������������������������������� 489
Entity Data Dictionary���������������������������������������������������������������������������������������������������������� 489
Entity Attribute Data Dictionary������������������������������������������������������������������������������������������� 491
Entity Relationship Data Dictionary: Equipment Failure Subject Area��������������������������������� 498
Entity Relationship Data Dictionary: Equipment Status History������������������������������������������� 500
Entity Relationship Data Dictionary: Plant Expense������������������������������������������������������������� 500
COUNT( ) Function��������������������������������������������������������������������������������������������������������������������� 501
AVG( ) Function��������������������������������������������������������������������������������������������������������������������� 512
MIN( ) and MAX( ) Functions������������������������������������������������������������������������������������������������� 514
GROUPING( ) Function���������������������������������������������������������������������������������������������������������� 526
STRING_AGG( ) Function������������������������������������������������������������������������������������������������������ 530
STDEV( ) and STDEVP( ) Functions���������������������������������������������������������������������������������������� 534
VAR( ) and VARP( ) Functions������������������������������������������������������������������������������������������������������ 543
Example 1: Rolling Variance������������������������������������������������������������������������������������������������ 544
Example 2: Variance by Quarter������������������������������������������������������������������������������������������� 547
Example 3: Variance by Year������������������������������������������������������������������������������������������������ 550

ix
Visit https://ebookmass.com
now to explore a rich
collection of eBooks and enjoy
exciting offers!
Table of Contents

Performance Considerations����������������������������������������������������������������������������������������������������� 553


Memory-Optimized Table Approach������������������������������������������������������������������������������������� 559
Seven-Million-Row Query: Performance Tuning����������������������������������������������������������������������� 570
Summary���������������������������������������������������������������������������������������������������������������������������������� 582

Chapter 9: Plant Use Case: Ranking Functions����������������������������������������������������� 583


Ranking Functions�������������������������������������������������������������������������������������������������������������������� 583
RANK( ) Function������������������������������������������������������������������������������������������������������������������ 584
Performance Considerations����������������������������������������������������������������������������������������������� 588
Performance Considerations����������������������������������������������������������������������������������������������� 594
Performance Considerations����������������������������������������������������������������������������������������������� 600
DENSE_RANK( ) Function����������������������������������������������������������������������������������������������������� 606
Performance Considerations����������������������������������������������������������������������������������������������� 611
NTILE Function��������������������������������������������������������������������������������������������������������������������� 616
Performance Considerations����������������������������������������������������������������������������������������������� 622
ROW_NUMBER( ) Function��������������������������������������������������������������������������������������������������� 626
Performance Considerations����������������������������������������������������������������������������������������������� 630
Summary���������������������������������������������������������������������������������������������������������������������������������� 633

Chapter 10: Plant Use Case: Analytical Functions������������������������������������������������ 635


Analytical Functions������������������������������������������������������������������������������������������������������������������ 635
CUME_DIST( ) Function�������������������������������������������������������������������������������������������������������� 637
Performance Considerations����������������������������������������������������������������������������������������������� 643
FIRST_VALUE( ) and LAST_VALUE( ) Functions��������������������������������������������������������������������� 648
Performance Considerations����������������������������������������������������������������������������������������������� 651
LAG( ) Function��������������������������������������������������������������������������������������������������������������������� 652
Performance Considerations����������������������������������������������������������������������������������������������� 656
LEAD( ) Function������������������������������������������������������������������������������������������������������������������ 665
Performance Considerations����������������������������������������������������������������������������������������������� 667
PERCENT_RANK( ) Function������������������������������������������������������������������������������������������������� 669
Performance Considerations����������������������������������������������������������������������������������������������� 671
PERCENTILE_CONT Function����������������������������������������������������������������������������������������������� 677
Performance Considerations����������������������������������������������������������������������������������������������� 680

x
Table of Contents

PERCENTILE_DISC( ) Function���������������������������������������������������������������������������������������������� 685


Performance Considerations����������������������������������������������������������������������������������������������� 688
Our Usual Report Table Solution������������������������������������������������������������������������������������������ 692
SQL Server Analysis Services��������������������������������������������������������������������������������������������������� 697
Summary���������������������������������������������������������������������������������������������������������������������������������� 714

Chapter 11: Inventory Use Case: Aggregate Functions���������������������������������������� 717


The Inventory Database������������������������������������������������������������������������������������������������������������ 717
The Inventory Data Warehouse������������������������������������������������������������������������������������������������� 719
Loading the Inventory Data Warehouse������������������������������������������������������������������������������������ 721
Aggregate Functions����������������������������������������������������������������������������������������������������������������� 735
COUNT( ), SUM( ), MAX( ), MIN( ), and AVG( ) Functions��������������������������������������������������������� 735
Performance Considerations����������������������������������������������������������������������������������������������� 739
AVG( ) Function�������������������������������������������������������������������������������������������������������������������� 743
Performance Considerations����������������������������������������������������������������������������������������������� 745
Data Warehouse Query�������������������������������������������������������������������������������������������������������� 747
Performance Considerations����������������������������������������������������������������������������������������������� 750
STDEV( ) Function���������������������������������������������������������������������������������������������������������������� 754
Performance Considerations����������������������������������������������������������������������������������������������� 758
Data Warehouse Query�������������������������������������������������������������������������������������������������������� 760
Performance Considerations����������������������������������������������������������������������������������������������� 764
VAR( ) Function��������������������������������������������������������������������������������������������������������������������� 766
Performance Considerations����������������������������������������������������������������������������������������������� 769
Enhancing the SSIS Package���������������������������������������������������������������������������������������������������� 772
Summary���������������������������������������������������������������������������������������������������������������������������������� 783

Chapter 12: Inventory Use Case: Ranking Functions�������������������������������������������� 785


Ranking Functions�������������������������������������������������������������������������������������������������������������������� 786
RANK( ) Function������������������������������������������������������������������������������������������������������������������ 786
Performance Considerations����������������������������������������������������������������������������������������������� 791
Querying the Data Warehouse��������������������������������������������������������������������������������������������� 796
DENSE_RANK( ) Function����������������������������������������������������������������������������������������������������� 802
Performance Considerations����������������������������������������������������������������������������������������������� 805
xi
Table of Contents

NTILE( ) Function������������������������������������������������������������������������������������������������������������������ 809


Performance Considerations����������������������������������������������������������������������������������������������� 813
ROW_NUMBER( ) Function��������������������������������������������������������������������������������������������������� 818
Performance Considerations����������������������������������������������������������������������������������������������� 823
Create an SSRS Report������������������������������������������������������������������������������������������������������������� 824
Report Builder Mini Tutorial������������������������������������������������������������������������������������������������� 828
Create a Power BI Report���������������������������������������������������������������������������������������������������� 855
Summary���������������������������������������������������������������������������������������������������������������������������������� 867

Chapter 13: Inventory Use Case: Analytical Functions����������������������������������������� 869


Analytical Functions������������������������������������������������������������������������������������������������������������������ 869
CUME_DIST( ) Function�������������������������������������������������������������������������������������������������������� 870
Performance Considerations����������������������������������������������������������������������������������������������� 876
FIRST_VALUE( ) and LAST_VALUE( ) Functions��������������������������������������������������������������������� 878
Performance Considerations����������������������������������������������������������������������������������������������� 883
LAG( ) Function��������������������������������������������������������������������������������������������������������������������� 885
Performance Considerations����������������������������������������������������������������������������������������������� 889
LEAD( ) Function������������������������������������������������������������������������������������������������������������������ 894
Performance Considerations����������������������������������������������������������������������������������������������� 900
PERCENT_RANK( ) Function������������������������������������������������������������������������������������������������� 907
Performance Considerations����������������������������������������������������������������������������������������������� 912
PERCENTILE_CONT( ) Function�������������������������������������������������������������������������������������������� 914
Performance Considerations����������������������������������������������������������������������������������������������� 919
PERCENTILE_DISC( ) Function���������������������������������������������������������������������������������������������� 925
Performance Considerations����������������������������������������������������������������������������������������������� 929
Overall Performance Considerations����������������������������������������������������������������������������������� 935
Report Builder Examples����������������������������������������������������������������������������������������������������������� 939
Summary���������������������������������������������������������������������������������������������������������������������������������� 947

Chapter 14: Summary, Conclusions, and Next Steps�������������������������������������������� 949


Summary���������������������������������������������������������������������������������������������������������������������������������� 949
Our Journey������������������������������������������������������������������������������������������������������������������������������ 949
About the Code�������������������������������������������������������������������������������������������������������������������������� 950
xii
Table of Contents

About the Database Folders������������������������������������������������������������������������������������������������������ 952


Data Used in the Examples������������������������������������������������������������������������������������������������������� 952
The Toolkit��������������������������������������������������������������������������������������������������������������������������������� 953
SQL Server�������������������������������������������������������������������������������������������������������������������������������� 954
SSMS���������������������������������������������������������������������������������������������������������������������������������������� 956
The Window Functions�������������������������������������������������������������������������������������������������������������� 959
The Visual Studio Community License�������������������������������������������������������������������������������������� 960
SSAS Projects���������������������������������������������������������������������������������������������������������������������� 962
SSIS Projects����������������������������������������������������������������������������������������������������������������������� 963
Power BI Web Scorecards, Dashboards, and Reports��������������������������������������������������������������� 964
Microsoft Excel Spreadsheets�������������������������������������������������������������������������������������������������� 965
SSAS Server������������������������������������������������������������������������������������������������������������������������������ 966
SSRS Server and Website��������������������������������������������������������������������������������������������������������� 968
Report Builder��������������������������������������������������������������������������������������������������������������������������� 970
Performance Analysis Tools������������������������������������������������������������������������������������������������������ 971
Estimated Query Plans�������������������������������������������������������������������������������������������������������� 972
Live Query Plans������������������������������������������������������������������������������������������������������������������ 973
DBCC������������������������������������������������������������������������������������������������������������������������������������ 974
IO and TIME Statistics���������������������������������������������������������������������������������������������������������� 974
STATISTICS PROFILE������������������������������������������������������������������������������������������������������������ 975
Where to Get the Tools�������������������������������������������������������������������������������������������������������������� 977
SQL Server Developer���������������������������������������������������������������������������������������������������������� 977
Visual Studio Community����������������������������������������������������������������������������������������������������� 978
SQL Server Data Tools��������������������������������������������������������������������������������������������������������� 979
SQL Server SSAS Project Support��������������������������������������������������������������������������������������� 980
SQL Server SSIS Project Support���������������������������������������������������������������������������������������� 981
SQL Server SSRS Project Support��������������������������������������������������������������������������������������� 982
Report Builder���������������������������������������������������������������������������������������������������������������������� 983
Power BI Desktop���������������������������������������������������������������������������������������������������������������� 984
Power BI Server������������������������������������������������������������������������������������������������������������������� 985

xiii
Table of Contents

Microsoft Excel�������������������������������������������������������������������������������������������������������������������� 986


SSMS����������������������������������������������������������������������������������������������������������������������������������� 987
Next Steps��������������������������������������������������������������������������������������������������������������������������������� 988
Thank You!�������������������������������������������������������������������������������������������������������������������������������� 988

Appendix A: Function Syntax, Descriptions���������������������������������������������������������� 989

Appendix B: Statistical Functions����������������������������������������������������������������������� 1009

Index������������������������������������������������������������������������������������������������������������������� 1035

xiv
About the Author
Angelo R. Bobak is a published author with more than three
decades of experience and expertise in the areas of business
intelligence, data architecture, data warehouse design, data
modeling, master data management, and data quality using
the Microsoft BI Stack across several industry sectors such as
finance, telecommunications, engineering, publishing, and
automotive.

xv
About the Technical Reviewer
Alicia Moniz is a leader in Data & AI at Microsoft, an
organizer for Global AI Bootcamp – Houston Edition, and
a #KafkaOnAzure Evangelista and prior was a three-time
Microsoft AI MVP. She is an active supporter of women in
technology and volunteers her time at events that help make
AI technology accessible to the masses. She is a co-author of
the Apress publication Beginning Azure Cognitive Services:
Data-Driven Decision Making Through Artificial Intelligence
along with fellow Microsoft MVPs Matt Gordon, Ida Bergum,
Mia Chang, and Ginger Grant. With over 14 years of experience in data warehousing
and advanced analytics, Alicia is constantly upskilling and holds more than 12 in-
demand IT certifications including AWS, Azure, and Kafka. She is active in the Microsoft
User Group community and enjoys speaking on AI, SQL Server, #KafkaOnAzure, and
personal branding for women in technology topics. Currently, she authors the blog
HybridDataLakes.com, a blog focused on cloud data learning resources, and produces
content for the YouTube channel #KafkaOnAzure.

xvii
Introduction
Welcome to my book, SQL Server Analytical Toolkit.
What’s this book about?
This is a book on applying Microsoft SQL Server aggregate, analytical, and ranking
functions across various industries for the purpose of statistical, reporting, analytical,
and historical performance analysis using a series of built-in SQL Server functions
affectionately known as the window functions!
No, not window functions like the ones used in the C# or other Microsoft Windows
application programming. They are called window functions because they implement
windows into the data set generated by a query. These windows allow you to control
where the functions are applied in the data by creating partitions in the query data set.
“What’s a partition?” you might ask. This is a key concept you need to understand to
get the most out of this book. Suppose you have a data set that has six rows for product
category A and six rows for product category B. Each row has a column that stores sales
values that you wish to analyze. The data set can be divided into two sections, one for
each product category. These are the partitions that the window functions use. You can
analyze each partition by applying the window functions (more on this in Chapter 1).
We will see that the window in each partition can be further divided into smaller
windows. The mechanism of a window frame allows you to control which rows in
the partition are submitted to the window function relative to the current row being
processed. For example, apply a function like the SUM() function to the current row being
processed and any prior rows in the partition to calculate running totals by month. Move
to the next row in the partition and it behaves the same.
The book focuses on applying these functions across four key industries: sales,
finance, engineering, and inventory control. I did this so that readers in these industries
can find something they are familiar with in their day-to-day job activities. Even if you
are not working across these industries, you can still benefit by learning the window
functions and seeing how they are applied.
Maybe you want to interview for a developer role in the finance sector? Or maybe
you work in engineering or telecommunications or you are a manufacturer of retail
products. This book will help you acquire some valuable skills that will help you pass the
job interview.
xix
Introduction

Although you could perform these functions with tools like Power BI, performing
these functions at the SQL level precalculates results and improves performance so that
reporting tools use precalculated data.
By the way, there are many books out there on SQL Server and window (or
windowing) functions. What’s so different about this book?

Approach
This book takes a cookbook approach. Not only are you shown how to use the functions,
but you are shown how to apply them across sales, finance, inventory control, and
engineering scenarios.
These functions are grouped into three categories, so for each industry use case we
look at, we will dedicate a chapter to each function category:

• Aggregate functions

• Analytical functions

• Ranking functions

For each function, a query is created and explained. Next, the results are examined
and analyzed.
Where applicable the results are used to generate some interesting graphs with
Microsoft Excel spreadsheets, like creating normal distribution charts for sales data.
Appendix A contains descriptions and syntax for these functions in case you are not
familiar with them, so feel free to examine them before diving into the book.
Key to mastering the concepts in this book is understanding what the OVER() clause
does. Chapter 1 starts off by defining what the OVER() clause is and how it is used with
the window functions.
Several diagrams clearly explain what data sets, partitions, and window frames are
and how they are key to using the window functions.
Each of the industries we identified earlier has three dedicated chapters, one for each
of the window function categories. Each chapter provides a specification for the query to be
written, the code to satisfy the specification, and then one or more figures to show the results.
The book is unique in that it goes beyond just showing how each function works; it
presents use case scenarios related to statistical analysis, data analysis, and BI (BI stands
for business intelligence by the way).

xx
Visit https://ebookmass.com
now to explore a rich
collection of eBooks and enjoy
exciting offers!
Introduction

The book also makes available all code examples including code to create and load
each of the four databases via the publisher's Google website.
Lastly, just enough theory is included to introduce you to statistical analysis in case
you are not familiar with terms like standard deviation, mean, normal distribution, and
variance. These are important as they will supply you with valuable skills to support your
business users and enhance your skills portfolio. Hey, a little business theory can’t hurt!
Appendix B has a brief primer on statistics, so make sure to check it out in case these
topics are new to you. It discusses standard deviation, variance, normal distribution,
other statistical calculations, and bell curves.
Back to the window functions. These functions generate a lot of numerical data. It’s
great to generate numbers with decimal points but even more interesting to graph them
and understand what they mean. A picture is worth a thousand words. Seeing a graph
that shows sales decreasing month by month is certainly worth looking at and should
raise alarms!
You can also use the Excel spreadsheets to verify your results by using the
spreadsheets’ built-in functions to make sure they match the results of your queries.
Always test your data against a set of results known to be correct (you might just learn
a little bit about Microsoft Excel too!). The spreadsheets used in this book will also be
available on the publisher's Google website.
The book includes tips and discussions that will take you through the process of
learning the SQL Server aggregate, ranking, and analytical functions. These are delivered
in a step-by-step approach so you can easily master the concepts. Data results are
analyzed so that you can understand what the function does and how the windows are
used to analyze the data work.

Expectations
Now that you know what you are in for, what do I expect from you?
Not much really, at a high level.
I expect you to be an intermediate to advanced SQL Server developer or data
architect who needs to learn how to use window functions. You can write ­medium-­
complexity queries that use joins, understand what a CTE (common table expression) is,
and be able to create and load database tables.
You could also be a tech-savvy business analyst who needs to apply sophisticated
data analysis for your business users or clients.

xxi
Introduction

Lastly, you could be a technology manager who wants to understand what your
development team does in their roles as developers. All will benefit from this book.
In conclusion, you need

• A keen interest in learning data analysis skills

• A basic knowledge of relational database technology and SQL skills

• A basic understanding of mathematical calculations like calculating


the average of values and performing basic arithmetic operations like
addition, subtraction, division, and multiplication

• Lastly, a working knowledge of SQL Server Management Studio


(SSMS), the tool we will use to create and execute the queries

In case you do not know how to use SSMS, there are many excellent YouTube videos
and sites that can show you how to use this tool in a short amount of time.
You can also check out my podcast “GRUMPY PODCAST 01 NAVIGATING SSMS” at
www.grumpyolditguy.com under the TSQL Podcasts menu selection in the menu bar.

What’s in It for You?


You, my dear reader, will learn how to use the Microsoft SQL Server analytical, aggregate,
and ranking functions. These are valuable skills that will enhance your capability to
develop solutions for your company role and the business users you support or will
support.

What Else Do You Get?


There are tons of code examples that you can access and play around with to become
familiar with the workings of the window functions. Practice makes perfect. Break the
code, modify it, and experiment. This is the best way to learn.

Note You can download the code from the publisher’s Google website at
https://github.com/Apress/SQL-Server-Analytical-Toolkit.

xxii
Random documents with unrelated
content Scribd suggests to you:
CHAPTER XXIV.
MR. BIRON’S REPENTANCE.

Then Bram went upstairs also, and knocked at Mr. Biron’s door.
“I’m going for the doctor now, Mr. Biron,” he called out without
entering. “I’ve come up to ask if there’s anything I can get for you
before I go.”
“Come in, Elshaw, come in!” cried Theodore, in a voice full of
tremulous eagerness. “I want to speak to you.”
Bram obeyed the summons, and found himself for the first time in
Mr. Biron’s bedroom, which was the most luxurious room in the
house. A bright fire burned in the grate, this being a luxury Theodore
always indulged in during the winter; the bed and the windows were
hung with handsome tapestry, and there were book-shelves, tables,
arm-chairs, everything that a profound study of the art of making
oneself comfortable could suggest to the fastidious Theodore.
He himself was sitting, wrapped in a cozy dressing-gown, with his
feet on a hassock by the fire. But he looked even more wretched
than he had done in his drenched clothes downstairs. There was an
unhealthy flush in his face, a feverish glitter in his eyes.
Bram saw something in his face which he had never seen there
before, something which suggested that the man had discovered a
conscience, and that it was giving him uneasiness.
“Sit down,” said he, pointing to a seat on the other side of the
fireplace. Bram wanted to go for the doctor, but the little man was so
peremptory that he thought it best to obey. “Elshaw, I think I’m going
to die.”
He uttered the words, as was natural in such a man, as if the whole
world must be struck into awe by the news. Bram inclined his head in
respectful attention, clasping his hands and looking at the fire. He
could not make light of this presentiment, which, indeed, he saw
reason to think was a well-founded one. Mr. Biron’s never robust
frame had been shaken sorely by his own excesses in the first place,
by erysipelas and consequent complications, and it was evident that
the experiences of this night had tried him very severely. He was still
shivering in a sort of ague: his eyes were glassy, his skin was dry. He
stood as much in need of a doctor’s aid as did his daughter.
But still Bram waited, struck by the man’s manner, and feeling that at
such a moment there was something portentous in his wish to
speak. Mr. Biron had something on his mind, on his conscience, of
which he wanted to unburden himself.
“Elshaw,” he went on after a long pause, “I’ve been to blame over
this—this matter of Claire and—and her cousin Chris.” He stared into
Bram’s face as if the young man had been his confessor, and rubbed
his little white hands quickly the one over the other while he spoke. “I
did it for the best, as I’m sure you will believe; I thought he was an
honorable man, who would marry her and make her happy. You
believe that, don’t you?”
Up to this moment Bram had believed this of Theodore; now for the
first time it flashed through his mind that it was not true. However, he
made a vague motion of the head which Theodore took for assent,
and the latter went on. He seemed to have become suddenly
possessed by a spirit of self-abasement, to feel the need of opening
his heart.
“There was no harm in my sending her to meet him—until—last
night,” pursued the conscience-stricken man. “I know I did wrong in
letting her go then!”
Bram sat up in his chair with horror in his eyes.
“You sent her? Begging, of course, as usual?”
The words were harsh enough, brutal, perhaps, in the
circumstances. But Bram’s feeling was too strong for him to be able
to choose the expression of it. That this father, knowing what he did
know, suspecting what he did suspect, should have sent his
daughter to ask Christian for money was so shocking to his feelings
that he was perforce frank to the utmost.
“What could I do? How could I help it? One has got to live, Claire as
well as I!” muttered Theodore, avoiding Bram’s eyes, and looking at
the fire. “Besides, we don’t know anything. We may be doing her
wrong in suspecting—what—what we did suspect,” said he
earnestly, persuasively. “She never told me that she went away with
him, never! I believe it’s a libel to say she did, the mere malicious
invention of evilly-disposed persons to harm my child.”
Bram was silent. These words chimed in so well with the hopes he
would fain have cherished that, even from the lips of Mr. Biron, they
pleased him in spite of his own judgment. Encouraged by the attitude
which he was acute enough to perceive in his companion, Theodore
went on—
“No, you may blame me as much as you like. You have more to
blame me for than you know. I’m going to tell you all about it—yes,
all about it.” And he began to play nervously with his handkerchief,
and to dart at Bram a succession of quick, restless glances. “But I
will hear nothing against my child. It’s not her fault that she’s the
daughter of her father, is it? But she’s not a chip of the old block, as
you know, Elshaw.”
Bram, who was getting anxious about leaving Claire so long without
medical attention, got up from his chair. He did not feel inclined to
encourage the evident desire of Mr. Biron for the luxury of
confession, of self-abasement. Like most vain persons, Theodore
was almost as willing to excite attention by the record of his
misdeeds as by any other way. And in the same way, when he felt
inclined to write himself down a sinner, nothing would content him
but to be the greatest sinner of them all. So he put up an imploring
hand to detain Bram.
“Wait,” he said petulantly. “Didn’t I say I had something to tell you?
It’s something that concerns Claire, too.”
At the mention of this name Bram, who had moved towards the door,
stopped, although he was inclined to think that all this was a mere
excuse on the part of Theodore to detain him, and put off the
moment when he should be left by himself.
“You remember that a box was sent to you—a chest, by the man at
East Grindley who left you his money?”
Bram nodded. His attention was altogether arrested now. Even
before Mr. Biron uttered his next words it was clear that he had a real
confession to make this time, that he was not merely filling up the
time with idle self-accusations.
“I went to your lodging the day it came, just to see that it was safe.
Your landlady had sent to ask me if I could take care of it for you, as
it was something of value. But I preferred to leave the responsibility
with her. In—in fact, Claire thought it best too.”
Bram read between the lines here, knowing what strong reasons
poor Claire would have for taking this view. Mr. Biron went on—
“There was a key sent with it.”
Bram looked up. He had found no key, and had been obliged to force
the padlock.
“The key was in a piece of paper. I found it on the mantelpiece. I—I
—well, of course, I had no right to do it; but I thought it would be
better for me to look over the contents of the chest to make sure they
were not tampered with in your absence.”
Bram was attentive enough now.
“So I unlocked the box, and I just glanced through the things it
contained. You know what I found; with the exception of this, that
there was some loose cash——”
Bram’s face grew red with sudden perception. But he made no
remark.
“I forget exactly what it was, something between two and three
hundred pounds. Now, I know that in strict propriety,” went on Mr.
Biron, in whom the instinct of confession became suddenly tempered
with a desire to prove himself to have acted well in the matter, “I
ought to have left the money alone. But it was strongly borne in upon
me at the moment that my dear daughter was worried because of
unpaid bills; and—and that, in short, it would be just what you would
wish me to do if you had been here, for me to borrow the loose
sovereigns, and apply them to our pressing necessities. I argued
with myself that you would even prefer, in your delicacy, that I should
not have to ask for them. And—in short, I may have been wrong, but
I—borrowed them.”
A strange light had broken on Bram’s face.
“Did Miss Claire know?” he asked suddenly in a ringing voice.
“Well—er—yes, in point of fact she did. She came to look for me,
and she, well, she saw me take them. She—in fact—wished me to
put them back; and I could not convince her that I was doing what
you would have wished.”
Bram’s brain was bursting. His heart was beating fast. He came
quickly towards Mr. Biron, and seized him by the wrist. There was no
anger in his eyes, nothing but a fierce, hungry hope. For he could not
despise Theodore more than he had done before, while the fact of
Claire’s shame on meeting himself might now bear a less awful
significance then it had seemed to do.
“She knew you had taken it? And you forced her to say nothing?”
cried he in passionate eagerness.
Mr. Biron was disconcerted.
“Well, er—I thought that—that perhaps, until I could see my way to
paying it back, it would be better——”
But Bram did not wait for more explanations. Indeed, he needed no
more. He saw in a flash what the shame was which he had seen in
Claire’s eyes when she met him after his return. It was the
knowledge that her father was a thief, that he had robbed Bram
himself, and that she could neither make restitution nor confession
for him.
And with this knowledge there flashed upon him the question—Was
this the only shame she had to conceal? He was ready, passionately
anxious, to believe that it was.
Mr. Biron was quick to take advantage of this disposition in Bram.
His mood of self-abasement seemed to have passed away as rapidly
as it had come. Not attempting to draw his hand away from Bram’s
grasp, he said buoyantly—
“But I could not let the matter rest. I felt that you might suspect her,
my child, of what her father, from mistaken motives perhaps, had
done——”
Bram cut him short.
“Oh, no, I shouldn’t have done that, Mr. Biron,” he said rather dryly.
“But you were very welcome to the money. And I am glad to think
you enjoyed yourself while it lasted.”
This thrust, caused by a sudden remembrance of the hunter and the
new clothes in which Theodore had been so smart at his expense,
was all the vengeance Bram took. He tore himself away as speedily
as possible, and ran off for the doctor with a lighter heart than he had
borne for many a day. Might not miracles happen? Might they not?
Bram asked himself something like this as he ran through the rain
over the sodden ground.
When he returned to the farmhouse with the doctor, Bram received a
great shock. For, on entering the kitchen, he found Mr. Cornthwaite
himself pacing up and down the room, while Joan watched him with
anxious eyes from the scullery doorway.
Josiah stopped short in his walk when the two men entered. He
nodded to Bram, and wished the doctor good-evening as the latter
passed through, and went upstairs, followed by Joan.
“Will you come through, sir?” said Bram. “There’s a fire in the
drawing-room.”
Mr. Cornthwaite, over whom there had passed some great change,
followed him with only a curt assent. Bram supposed that even he
had been touched to learn that the woman of whom he had come in
search was so ill as to be past understanding that her persecution
had already begun. He stood in front of the fire, with his hat in one
hand and his umbrella in the other, with his back to Bram, in dead
silence for some minutes.
Then he turned abruptly, and asked in a stern, cold voice, without
looking up from the floor, on which he was following the pattern of
the carpet with the point of his umbrella—
“Did that scoundrel Biron get back home all right?”
“He’s got home, sir, but he’s very ill. He’s caught cold, I think.”
“He was not molested, attacked again, by the woman, the woman
Tyzack, who threw the vitriol over him before?”
“No, sir. She followed him, but he lost sight of her before he got
here.”
Mr. Cornthwaite nodded, and was again silent for some time. Bram
was much puzzled. Instead of the fierce resentment, the savage
anger which had possessed the bereaved father immediately after
the loss of his son there now hung over him a gloomy sadness
tempered by an uneasiness and irresolution, which were new
attributes in the business-like, strong-natured man.
The silence had lasted some minutes again, when he spoke as
sharply as before.
“I came to see the daughter, Claire Biron. But I’m told—the woman
tells me—that she is ill, and can’t see any one. Is that true?”
“Yes, sir. She is delirious.”
Mr. Cornthwaite turned away impatiently, and again there was a
pause. At last he said in the same sharp tone—
“You brought her back home, I suppose?”
“Yes. At least I followed her, and when she grew too tired to walk
alone I caught her up, and helped her along.”
Mr. Cornthwaite looked at him curiously. The little room was ill-
lighted, by two candles only and the red glow of the fire. He could
see Bram’s face pretty well, but the young man could not see his.
“Still infatuated, I see?” said Josiah in a hard, ironical voice.
Bram made no answer.
“You intend to marry her, I suppose?” went on Mr. Cornthwaite in a
harder tone than ever.
Bram stared. But he could see nothing of Mr. Cornthwaite’s features,
only the black outline of his figure against the dim candle-light.
“No, sir,” said he steadily. “I only hope to be able to save her life.”
“And how do you propose to do that?”
“Sir, you know best.”
His voice shook, and he stopped. There was silence between them
till they heard the footsteps of the doctor and Joan coming down the
stairs. Mr. Cornthwaite opened the door.
“Well, Doctor,” said he, “what of the patients?”
There was more impatience than solicitude in his tone.
“They’re both very ill,” answered the doctor. “They ought each to
have a nurse, really.”
“Very well. Can you engage them, Doctor? I’ll undertake to pay all
the expenses of their illness.”
The doctor was impressed by this generosity; so was Bram, but in a
different way. What was the reason of this sudden consideration, this
unexpected liberality to the poor relations whom he detested, and to
whom he imputed the death of his son?
“What’s the matter with them?” went on Mr. Cornthwaite in the same
hard, perfunctory, if not slightly suspicious tone.
“Pneumonia in Mr. Biron’s case, brought on by exposure to wet and
cold, no doubt. He has just had a severe shivering fit, and his pulse
is up to a hundred and four. We must do the best we can, but he’s a
bad subject for pneumonia, very.”
“And the daughter?”
“Acute congestion of the brain. She’s delirious.”
“Ah!”
Mr. Cornthwaite seemed satisfied now that he had the doctor’s
assurance that the illness was genuine. He made no more inquiries,
but he followed the medical man into the hall and to the front door.
The doctor perceived that it was locked and bolted at the top and
bottom.
“All right,” said he, “I’ll go through the other way.”
And he made his way to the kitchen, followed by Mr. Cornthwaite
and Bram.
As he opened the door which led into the kitchen, the wind blew
strongly in his face from the outer door, which was wide open. The
rain was sweeping in, and the tablecloth was blown off into his face
as he entered. At the same moment Joan, who had gone into the
back kitchen to prepare something the doctor had ordered, made her
appearance at the door between the two rooms.
“I shouldn’t leave this door open,” said the doctor as he crossed the
room to shut it. “The wind blows through the whole house.”
Joan stared.
“Ah didn’t leave it open, sir,” said she. “Ah’ve only just coom through
here, and it were shut then. Some one’s been and opened it.”
Bram gave a glance round the room, and then opened the door
through which he and the others had just come to examine the hall.
“What’s the matter?” asked Mr. Cornthwaite sharply. He had bidden
the doctor a hasty good-bye, afraid of the condolences which he saw
were on the tip of his tongue.
Bram, with a candle in his hand, was peering into the dark corners.
“I was just thinking, sir, that perhaps Meg Tyzack had got in while we
were talking in the drawing-room,” said he. “Mr. Biron made me bolt
the doors to keep her from getting in. He seemed to be afraid she
would follow him into the house.”
The words were hardly uttered, when from the floor above there
came a piercing scream, a woman’s scream.
“Claire!” shouted Bram, springing on the stairs.
But before he could mount half a dozen steps a wild figure came out
of Claire’s room, and rushed to the head of the staircase in answer
to his call. But it was not Claire. It was, as Bram had feared, Meg
Tyzack, recognizable only by her deep voice, by her loud, hoarse
laugh, for the figure itself looked scarcely human.
Standing at the top of the stairs, with her arms outstretched as if to
prevent any one’s passing her on the way up, the gaunt creature
seemed to be of gigantic height, and looked, with her loose,
disordered hair and the rags which hung down from her arms instead
of sleeves, like a witch in the throes of prophecy.
“Stand back! Stand back! Leave her alone!” she cried furiously, as
Bram rushed up the stairs, and struggled to get past her. She flung
her arms round him, laughing discordantly, and clinging so tightly
that without hurting her he would have found it impossible to
disengage himself.
“What has she done? What has she done?” asked Mr. Cornthwaite
in a loud, hard, angry voice as he came to Bram’s assistance.
At the first sound of Mr. Cornthwaite’s voice, Meg’s rage seemed
suddenly to disappear, to give place to a fit of strange gloom, quite
as wild, and still more terrible to see. Releasing Bram, who ran past
her, she leaned over the banisters, and looked straight into Mr.
Cornthwaite’s haggard face.
“What has she done? What have I done?” said she in a horrible
whisper. “Why, I’ve done the best night’s work that’s ever been done
on this earth, that’s what I’ve done. I’ve sent the man and the woman
I hated both to——. Ha! ha! ha!”
With a shrieking laugh she leapt past him to the bottom of the stairs.
CHAPTER XXV.
MEG.

Bram Elshaw heard Meg’s wild words as he rushed along the


corridor towards the room out of which she had just come—Claire’s
room, as he guessed, with a sob of terror rising in his throat.
The door was open. On the floor, just inside, lay what Bram at first
thought to be Claire’s lifeless body. Meg had dragged her off the bed,
and flung her down in an ecstasy of mad rage.
But even as he raised her in his arms, before the frightened Joan
had run up to his aid, Bram was reassured. The girl was
unconscious, but she was still breathing. Joan wanted to send him
away.
“Leave her to me, sir, leave her to me. You can goa and fetch t’
doctor back,” cried she, as she tried jealously to take Claire out of his
arms.
But Bram did not seem to hear her. He was staring into the
unconscious face as if this was his last look on earth. He hung over
her with all the agony of his long, faithful, unhappy love softening his
own rugged face, and shining in his gray eyes.
“Oh, Claire, Claire, my little Claire, my darling, are you going away?
Are you going to die?”
The words broke from his lips, hoarse, low, forced up from his heart.
He did not know that he had uttered them; did not know that he was
not alone with the sick girl. Joan, whose tears were running down
her own face, suddenly broke into a loud sob, and shook him roughly
by the shoulder.
“Put her down; do ee put her down,” she said peremptorily. “Do ye
go for to think as your calling to her will do her any good? Goa ee for
t’ doctor. And God forgive me for speaking harsh to ye, sir.”
“Oh Claire, Claire, my little Claire, are you going to die?”—Page
200.
And the good woman, seeing the strange alteration which came over
Bram’s face as he raised his eyes from the girl’s face to hers as if he
had come back from another world, changed her rough touch to a
gentle pat of his shoulder, and turned away sobbing.
Bram lifted Claire from the floor with the easy strength of which his
spare, lean frame gave no promise, and placed her tenderly on the
bed. Then he held one of her hands for a moment, leaned over her,
and kissed her forehead with the lingering but calm tenderness of a
mother to her babe.
“A’ reght,” muttered he to Joan, falling once more into the broad
Yorkshire he had dropped for so long, “Ah’m going.”
At the foot of the stairs he was brought suddenly to full remembrance
of the hard, matter-of-fact world of every day. Mr. Cornthwaite was
standing, cold and grave, buttoning up his coat, ready to go.
“Where are you going?” asked he shortly.
“For the doctor again, sir. Meg has nearly done for her, for Miss
Claire.”
Mr. Cornthwaite uttered a short exclamation, which might have been
meant to express compassion, but which was more like indifference,
or even satisfaction. So Bram felt, in a sudden transport of anger.
“And the old man—Mr. Biron, what did she do to him?”
Bram was silent. He remembered Meg’s ferocious words, her
triumphant cry that she had killed both the woman and the man she
hated; and as the remembrance came back he turned quickly, and
went in the direction of Theodore’s room. But Mr. Biron was lying
quietly in bed, apparently unaware that anything extraordinary had
happened. For when he saw Bram he only asked if he were going to
stay with him. Bram excused himself, and left the room.
“Mr. Biron’s all right, sir,” he said to Mr. Cornthwaite, who had by this
time reached the door, impatient to get away.
The only answer he got was a nod as Mr. Cornthwaite went out of
the house.
Bram had not to go far before he found some one to run his errand
for him, so that he was able to return to the house. His mind was full
of a strange new thought, one so startling that it took time to
assimilate it. He sat for a long time by the kitchen fire, turning the
idea over in his mind, until the doctor returned, and went away again,
after reporting that Claire was not so much injured by the woman’s
violence as might have been feared.
It was very late when a nurse, the only one to be got on the spur of
the moment, arrived at the farmhouse. Bram was still sitting by the
kitchen fire. When she had been installed upstairs Joan came down
for a little while.
“What, you here still, Mr. Elshaw?” cried she.
“Well, you might have known I should be,” he answered with a faint
smile. “I’m here till I’m turned out, day and night now!”
“Why, sir, ye’d best goa whoam,” said Joan kindly. “Ye can do no
good, and Ah won’t leave her, ye may be sure. Ah’ve sent word
whoam as they mun do wi’out me till t’ mornin’.”
“Ah, but I’ve something to say to you, Joan. Look here; doesn’t it
seem very strange that Mr. Cornthwaite when he is half-mad with
grief at his son’s death, should come all the way out here to see his
niece? And that he should say nothing more about—about the death
of his son? And that he should give orders for a nurse to come, and
undertake to pay all the expenses of her illness? Doesn’t it look as if
——”
Joan interrupted him with a profound nod.
“Lawk-a-murcy, ay, sir. Ah’ve thowt o’ that too,” said she in an eager
whisper. “And don’t ye think, sir, as it’s a deal more likely that that
poor, wild body Meg killed Master Christian wi’ her strong arms and
her mad freaks than that our poor little lass oop yonder did it?”
Bram sprang up.
“Joan, that’s what I’ve been thinking myself ever since the woman
rushed out from here. She said she’d sent to h—— the woman and
the man she hated, didn’t she? Well, if Claire was the woman, surely
Mr. Christian must have been the man!”
They stared each into the face of the other, full of strong excitement,
each deriving fresh hope from the hope each saw in the wide eyes of
the other. At last Joan seized his hand, and wrung it in her own
strong fingers with a pressure which brought the water to his eyes.
“You’ve got it, Mr. Bram, you’ve got it, Ah believe!” cried she in a
tumult of feeling. “Oh, for sure that’s reght; and our poor little lass is
as innocent of it as t’ new-born babe!”
Full of this idea, Bram conceived the thought of making inquiries at
Meg’s own home, and he started at once with this object.
It was now very late, past eleven o’clock; but his uneasiness was too
great to allow him to leave the matter till the morning. So, at the risk
of reaching the farmhouse, where Meg’s parents lived, when
everybody was in bed, he took a short cut across the wet, muddy
fields, and arrived at his destination within an hour.
The rain had ceased by this time, and the moon peeped out from
time to time, and from behind a mass of straggling clouds. The little
farm lay in a nook between two hills, and as Bram drew near he saw
that a light was still burning within. In getting over a gate he made a
little noise, and the next moment he saw a woman’s figure come
quickly out of the farmhouse.
“Meg, is that you, Meg?” asked a woman’s voice anxiously.
“No,” said Bram, “it isn’t Meg, ma’am. It’s me, from Hessel, come to
ask if she’d got safe home.”
She came nearer, and peered into his face.
“And who be you?”
“My name’s Bram Elshaw. I’m a friend of the Birons at Duke’s Farm.”
“Ah!”
There was a world of sorrow, of significance, in the exclamation.
After a pause, she said, not angrily, but despondently—
“Then maybe you know all about it? Maybe you can tell me more
than I know myself? Have you seen anything of Meg—she’s my
daughter—this evening?”
Bram hesitated. The woman went on—
“Oh, don’t be afraid to speak out, sir, if it’s bad news. We’ve been
used to that of late; ever since our girl took up with t’ gentleman that
has treated her so bad. It’s no use for to try to hide it; t’ poor lass
herself has spread t’ news about. She’s gone right out of her mind, I
do believe, sir. She wanders about, so I often have to sit up half t’
night for her, and she never gives me a hand now with t’ farm work.
And as neat a hand in t’ dairy as she used to be! Well, sir, what is it?
Has she made away with herself?”
“She came to Duke’s Farm to-night, and attacked Miss Biron,” said
Bram.
“Well, she was jealous,” said Meg’s mother, who seemed to be less
afflicted with sentiment concerning her daughter than with vexation
at the loss of her services. “The lass found it hard she should lose
her character, and then t’ young gentleman care more for his cousin
all t’ time. Not but what Meg was to blame. She used to meet him
when she knew he was going to Duke’s Farm, up in t’ ruined
cottages on top of t’ hill at Hessel. So I’ve learnt since. Folks tell you
these things when it’s too late to stop them!”
Bram remembered the night on which he had heard the voices in the
dismantled cottages, and he remembered also with shame that he
had conceived the idea that Christian’s companion might be his
cousin.
“Did she tell you where she was going when she went out to-night?”
asked Bram.
“She hasn’t been home since this afternoon,” replied Meg’s mother.
“She went out before tea, muttering in her usual way threats against
him and her,—always him and her. She never says any different. I’ve
got used to her ravings; I don’t think she’d do any real harm unless
to herself, poor lass!”
“I’m afraid she has this time,” said Bram gravely. “I don’t know
anything more than I’ve told you; but I’m afraid you must be prepared
for worse news in the morning.”
Startled, the woman pressed for an explanation. Bram, having really
nothing but suspicion to go upon, could tell her nothing definite. But
his suspicion was so strong that he felt no diffidence about preparing
Meg’s mother for a dreadful shock. On the other hand, he was able
to assure her that, whatever she might have done, her manifestly
disordered state of mind would be considered in the view taken of
her actions.
Then he returned to Hessel, tried the door of Duke’s Farm, and
found it locked for the night. He went round to the front, looked up at
the dim light burning in Claire’s room with a fervent prayer on his
lips, and then climbed the hill to his own lodging.
On inquiry at the farm next morning on his way to his work Bram
learnt from the nurse, who was the only person he could see, that
while Mr. Biron had had a very bad night, Claire was as well as could
be expected. No decided improvement could be reported as yet, nor
could it indeed be expected. But she was quieter, and her
temperature had gone down, temporarily at least.
He went on his way feeling a little more hopeful, after impressing
upon the nurse to keep the doors locked for fear of any further
incursions from poor, crazy Meg Tyzack.
On arriving at the works, he saw, as was to be expected after the
tragedy of the preceding evening, an unusual stir among the
workmen, who were standing about the entrance, talking in eager
and excited tones. One of the workmen saluted Bram, and asked
him if he had “heard t’ fresh news.”
“What’s that?” asked Bram.
“Coom this weay, sir; Ah’ll show ye.”
Bram, with a sick terror at his heart, asking himself what new horror
he should be called upon to witness, followed the man through the
works. The rain had come on again, a drizzling, light rain, which was
already turning the morning’s dust into a thick, black paste. They
passed across the yards and through the sheds, until again they
reached the spot where the railway divided the works into two parts.
An exclamation broke from Bram’s lips.
“Not another—accident—here?”
For there was quite a large throng of workmen scattered over the
lines on the opposite side, and culminating in one dense group not
far from the spot where he had found Christian on the previous night.
“Ay, sir, it’s a woman this time.” And his voice suddenly fell to a
hoarse whisper. “T’ woman as killed Mr. Christian! T’ poor creature
was crazed, for sure! She got in here, nobody knows how, this
morning; an’ she must ha’ throwed herself down on t’ line pretty nigh
t’ place where she throwed him down last neght. She must ha’
waited for t’ mornin’ oop train. Anyway, we fahnd her lyin’ there this
mornin’, poor lass!”
Bram had reached the group. He forced his way through, and looked
down at the burden the men were carrying towards the very shed
under the roof of which Chris had died.
The mutilated body, which had been decapitated by the heavy
wheels of the train, was only recognizable by the torn and stained
clothing as that of Meg Tyzack.
Bram staggered away, with his hand over his eyes.

You might also like