0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[SQLServer]Window関数

Last updated at Posted at 2024-06-24

1. サンプルテーブルの作成

CREATE_TABLE_Sales.sql
CREATE TABLE Sales (
    SaleID INT IDENTITY(1,1) PRIMARY KEY,
    ProductName NVARCHAR(100),
    SaleAmount DECIMAL(10, 2),
    SaleDate DATE
);

2. サンプルデータの挿入

INSERT_Sales.sql
INSERT INTO Sales (ProductName, SaleAmount, SaleDate) VALUES ('Product A', 100.00, '2024-06-01');
INSERT INTO Sales (ProductName, SaleAmount, SaleDate) VALUES ('Product B', 150.00, '2024-06-01');
INSERT INTO Sales (ProductName, SaleAmount, SaleDate) VALUES ('Product C', 200.00, '2024-06-02');
INSERT INTO Sales (ProductName, SaleAmount, SaleDate) VALUES ('Product D', 250.00, '2024-06-02');
INSERT INTO Sales (ProductName, SaleAmount, SaleDate) VALUES ('Product E', 300.00, '2024-06-02');

3. Window関数の使用例

SELECT_Sales.sql
SELECT SaleID, ProductName, SaleAmount, SaleDate,
       RANK() OVER (PARTITION BY SaleDate ORDER BY SaleAmount DESC) AS DailyRank
FROM Sales;

実行結果

SaleID ProductName SaleAmount SaleDate DailyRank
2 Product B 150.00 2024-06-01 1
1 Product A 100.00 2024-06-01 2
5 Product E 300.00 2024-06-02 1
4 Product D 250.00 2024-06-02 2
3 Product C 200.00 2024-06-02 3

4. 解説

・PARTITION BY
Window関数が適用されるデータのグループを指定します。この例では、SaleDateごとにグループ化しています。

・ORDER BY
グループ内の行をどのように並べ替えるかを指定します。この例では、SaleAmountの降順で並べ替えています。

・RANK()
Window関数として使用され、各グループ内の行にランクを付けます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?