Skip to content
Advertisement

Alter SQL column based on comparison of number of elements

I have a table with columns (Id, Prod, Id) and I must create a (Flag) like this:

This (Flag) is created by grouping by (Id2) and assigning 0 for the lowest (Id) and 1 otherwise.

I tried using group by to no avail. How can I do that?

Advertisement

Answer

You can use a case expression with a windowed function:

Example Fiddle

You didn’t tag a DBMS, so I’ve gone with SQL Server, but this should work for most.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement