Apologies in advance if I am asking in the wrong forum.
I am trying to get the first attribute value for each ID in my table based on the ID's starting week. When using the min() function on weekkey, my query is returning more than one value if an ID has more than one attribute.
Drop table if Exists table1
CREATE TABLE table1 (
IDNumber INT NOT NULL,
Attribute VARCHAR(30) NOT NULL,
WeekKey INT NOT NULL,
);
INSERT INTO table1
(IDNumber, Attribute, WeekKey)
VALUES
(1,'a',1),
(1,'a',2),
(1,'b',3),
(2,'c',1),
(3,'a',1),
(3,'c',2);
Select IDNumber, Attribute, Min(WeekKey) StartWeek
From Table1
Group by IDNumber, Attribute
Order by IDNumber, Attribute
My goal output would be:
1 a 1
2 c 1
3 a 1
My current output is:
1 a 1
1 b 3
2 c 1
3 a 1
3 c 2
Does anyone have an idea how to accomplish my goal without too many extra steps?
Thanks,
Taylor
Best Answer
You need to use a window function like
ROW_NUMBER()
to generate a unique ID sorted on theWeekKey
partitioned byIDNumber
.