Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating first record of a group of records t-sql

I have a table like this

CREATE TABLE [dbo].[tblUserLink](
    [IDUserLink] [int] IDENTITY(1,1) NOT NULL,
    [IDUser] [int] NOT NULL,
    [IDRegie] [varchar](50) NOT NULL,
    [DefaultAgency] [bit] NULL
)

I'm looking for a query /script to update the field DefaultAgency. I'd like to set it to 1 for the first record that comes for each group of record with a same IDUser.

example :

IDUserLink IDUser IDRegie DefaultAgency (Goal)
1          1      1       null           DefaultAgency to be set to 1
2          1      2       null
3          1      3       null
4          2      2       null           DefaultAgency to be set to 1
5          2      1       null     
6          3      1       null           DefaultAgency to be set to 1
 ...etc 

Can I achieve this using a simple sql query or should I script it ?

like image 401
Arno 2501 Avatar asked Oct 17 '12 08:10

Arno 2501


People also ask

How do you select the first record in a group by SQL?

First, you need to write a CTE in which you assign a number to each row within each group. To do that, you can use the ROW_NUMBER() function. In OVER() , you specify the groups into which the rows should be divided ( PARTITION BY ) and the order in which the numbers should be assigned to the rows ( ORDER BY ).

Can we use top with Group By clause?

Typically, these are accomplished using the TOP or LIMIT clause. Problem is, Top N result sets are limited to the highest values in the table, without any grouping. The GROUP BY clause can help with that, but it is limited to the single top result for each group.

How do you UPDATE a specific record in SQL?

First, specify the table name that you want to change data in the UPDATE clause. Second, assign a new value for the column that you want to update. In case you want to update data in multiple columns, each column = value pair is separated by a comma (,). Third, specify which rows you want to update in the WHERE clause.


1 Answers

update tblUserLink
set DefaultAgency = 1
where IDUserLink in
(select min(IDUserLink) from tblUserLink group by IDUser)
like image 117
podiluska Avatar answered Sep 24 '22 00:09

podiluska