Với bài tập lần trước các anh chị đã làm quen với sub query và with CTE. Tuy nhiên với subquery hay CTE chúng ta chỉ sử dụng kết quả đó trong một lần thực thi câu query vậy câu hỏi đặt ra có cách nào dùng lại các kết quả query nhiều lần trong 1 session không?
chúng ta có bảng [Sales].[SalesPersonQuotaHistory] chứa thông tin doanh thu theo từng năm của từng nhân viên. Hãy tìm ra best salers của mỗi năm và doanh thu của họ
đầu tiên ta cần tính tổng quota của từng nhân viên theo năm
Sau đó ta cần tìm ra chỉ số sale_quota lớn nhất theo năm dựa theo số tổng
ta dùng lại 2 bảng kết quả join lại với nhau theo 2 cột YEAR_QUOTA VÀ SALES
Có cách nào nhanh hơn cách trên không?
Cú pháp
Dựa vào bảng [HumanResources].[Employee] và HumanResources].[EmployeePayHistory] tìm ra tên và sắp sếp theo ranking mức lương trung bình của jobtitle "Production Technician - WC30"
Ranking Products by Sales:
Write a SQL query to rank products based on their total sales amount in descending order. Include the product name, total sales amount, and the corresponding rank for each product.
Monthly Sales Growth:
Calculate the monthly sales growth for each product category. Display the product category, the month, and the percentage growth compared to the previous month. Order the results by category and month.
Running Total of Orders:
Calculate the running total of orders for each day in the order table. Display the order date, the number of orders on that date, and the running total of orders up to that date.
Top 5 Customers by Total Revenue:
Find the top 5 customers who have generated the highest total revenue. Display their customer names, customer IDs, and the total revenue they have contributed.
Calculating Percentile:
Calculate the 25th, 50th, and 75th percentile of the total sales amount for each product category. Display the category name and the respective percentile values.
Sales Contribution Ratio:
Determine the sales contribution ratio of each product within its category. The sales contribution ratio of a product is the percentage of the product's sales amount compared to the total sales amount of its category. Display the product name, sales amount, category name, and the contribution ratio.
Top 3 Products per Category:
Find the top 3 products with the highest sales amount for each product category. Display the category name, product name, and sales amount for each product.
Lag and Lead Calculation:
Calculate the lag and lead of the sales amount for each product. The lag represents the previous sales amount, and the lead represents the next sales amount. Display the product name, sales amount, lag, and lead.