Consider the following table in SQL Server:
I want to write a SQL query to generate the column Indicator
. This column should be set to 1 on the first occurrence of Flag = 1
for each category.
For instance, for Category A, column Flag
is set to 1 for the dates 1/3/2019, 1/4/2019, 1/5/2019, 1/6/2019. Since 1/3/2019 is the earliest date when Flag
was set to 1, the Indicator
column for that record should also be set to 1.
What SQL Server query should I write for this?
PS: The figure already shows the desired output for the Indicator
column.
Below is the code to generate the table in SQL Server:
CREATE TABLE myTable
(
Category CHAR(1),
Date DATE,
Flag INT
)
INSERT INTO myTable (Category, Date, Flag)
VALUES ('A', '2019-01-01', 0), ('A', '2019-02-01', 0),
('A', '2019-03-01', 1), ('A', '2019-04-01', 1),
('A', '2019-05-01', 1), ('A', '2019-06-01', 1),
('B', '2019-01-01', 0), ('B', '2019-02-01', 0),
('B', '2019-03-01', 0), ('B', '2019-04-01', 0),
('B', '2019-05-01', 1), ('B', '2019-06-01', 1),
('C', '2019-01-01', 0), ('C', '2019-02-01', 0),
('C', '2019-03-01', 0), ('C', '2019-04-01', 1),
('C', '2019-05-01', 1), ('C', '2019-06-01', 1),
('C', '2019-07-01', 1)