Problem Description / Requirement

The marketing department of db Berater GmbH is planning a private event for its 10 TOP customers. The marketing department provides the following guidelines for selecting customers:

  • Only customers with at least 3 orders in the last quarter of 2022 may be considered
  • The 10 customers with the most orders in the last quarter of 2022 should be considered
  • If more customers have had the same number of orders in the last quarter of 2022, they should also be invited – regardless of sales.
  • The total amount of sales must consider only the last 3 orders from 2022

The image on the left shows the marketing department’s blueprint with all the relevant attributes the team needs.

Challenge

Create the required query to meet the needs of the Marketing department. This query will be used in the Marketing department in a dashboard that is updated every 5 minutes. It is important that the query runs as quickly as possible. The department’s requirement is a runtime of less than 5 seconds!

Category
  • Writing efficient queries
  • Level 200
Technical information

When creating the challenge, two tables are created as heaps.

Table Name Number of Rows Storage Space
dbo.customers 1.607.957 219 MB
dbo.orders 2.275.781 296 MB
Solution

The key to the requirements was the use of “WITH TIES” and either the window function ROW_NUMBER() or CROSS APPLY as the operator.

Challenge #1 – Solution

Connect to Microsoft SQL Server

SQL Server: sqlchallenges.germanywestcentral.cloudapp.azure.com
Port: 1433
Version:
16.0.4165.4
Edition: Developer Edition
Authentication Type: SQL Server Authentication
Login Name: sqlchallenge
Password: sqlchallenge#2025!
Encryption Mandatory
Trust Server Certificate: True

 

Improve Your Skills as Query Tuner for SQL Server

During this workshop, you’ll gain the expertise and confidence needed to diagnose and fine-tune slow-performing queries, resulting in improved database responsiveness and end-user satisfaction. Whether you’re an experienced database administrator, developer, or data analyst, this workshop will equip you with the knowledge and practical skills to tackle the most challenging query optimization tasks.

Improve your skills as a database developer

Improve Your Skills as a Database Developer for SQL Server

In this workshop, we will cover a wide range of topics and techniques that are essential for modern database developers working with SQL Server. From fundamental concepts to advanced best practices, you’ll gain the knowledge and practical experience needed to excel in your role.