Milacay Milacay - 4 months ago 12
SQL Question

SQL Server 2008 - Fill Same Value Based On The Name

I am working on a query and having a difficult time to figure out how to fill the same value based on one column. Let me explain what I am trying to accomplish....

Says, I have a table like this below with too columns: Name & Value. So, "Select Name, Value FROM Table1 Order By Name" will produce the following result.

Table1

Name Value
AAA 111
AAA
BBB 222
BBB
BBB
BBB
CCC 333
CCC
DDD 444
DDD
DDD


Now, What I am trying to accomplish is producing the result below with the "Select .... from Table1" query.

Table1

Name Value
AAA 111
AAA 111
BBB 222
BBB 222
BBB 222
BBB 222
CCC 333
CCC 333
DDD 444
DDD 444
DDD 444


Please help and provide the sample code if possible.

Thanks in advance

Answer

You can use MAX() as a window function:

SELECT Name, Value,
       MAX(Value) OVER (PARTITION BY Name) as imputed_name
FROM Table1
ORDER BY Name;