I don't understand why I can't I simply SELECT MAX(Weight)
.
This is my code:
CREATE TABLE Table1
(
"ID" varchar(8),
"ItemName" varchar(12),
"Floor" varchar(11),
"Weight" int
);
INSERT INTO Table1 ("ID", "ItemName", "Floor", "Weight")
VALUES
('6DC85C23', 'Item one', 'first floor', 0),
('6DC85C24', 'Item two', 'first floor', 2),
('6DC85C25', 'item ten', 'first floor', 3),
('B2B4DC7B', 'item another', 'first floor', 0);
SELECT
tb.Id, tb.ItemName, tb.Floor, MAX(Weight)
FROM
Table1 tb
GROUP BY
tb.Id, tb.ItemName, tb.Floor
I need to return only rows that has MAX weight for every Id. It should return just two rows like this:
Id | ItemName | Floor | (No column name) |
---|---|---|---|
6DC85C25 | item ten | first floor | 3 |
B2B4DC7B | item another | first floor | 0 |
But it returns this data instead - why? What am I doing wrong it just a simple table! Why max function does not work for me as expected?
Id | ItemName | Floor | (No column name) |
---|---|---|---|
6DC85C23 | Item one | first floor | 0 |
6DC85C23 | Item two | first floor | 2 |
6DC85C23 | Item ten | first floor | 3 |
B2B4DC7B | item another | first floor | 0 |
Here is fiddle
I also tried this
select top 1 with ties
ID
,ItemName
,Floor
,Weight
from Table1
order by row_number() over (partition by ID order by Weight desc)
From this question, but this does not work, I don't know why.