SQL Server Row Number Counter

Asked

Viewed 794 times

0

how do I perform a counter on the sql server from a certain number. Example below.

Current result

Ticket   Ação
42977     1
42977     2

Expected result

42977     3
42977     4
42977     5

---Below the query---

The first Union: All with action 1 The second Union: All with the action 2 The third Union: Here it is to start counting from the number 3

1st Action (Description of the Call)

select
s.id Ticket,
CONVERT(VARCHAR(10), s.insert_time, 103) + ' '  + convert(VARCHAR(8), s.insert_time, 14) [Data/Hora],
'Pública' [Ação é Pública? (Pública/Interna)],
case when u.ref_id = '1' then '454' else u.ref_id end as Gerador,
description Descricao,
'1' [Seq Ação]
from service_req s
left join sysaid_user u on s.request_user = u.user_name -- Solicitante Gerador da 1º Ação (Descrição do Chamado)
where s.id in(42977)
union all

2nd Action (Notes of the Called)

select
s.id Ticket,
CONVERT(VARCHAR(10), s.insert_time, 103) + ' '  + convert(VARCHAR(8), s.insert_time, 14) [Data/Hora],
'Pública' [Ação é Pública? (Pública/Interna)],
case when u.ref_id = '1' then '454' else u.ref_id end as Gerador, --Responsável
'Todas as anotações (sistema antigo): ' +
s.notes + ' ' as Descrição,
'2' [Seq Ação]
from service_req s
left join sysaid_user u on u.user_name = s.responsibility --Responsável
where s.id in(42977)
union all

Other Actions of the Call (Messages) Count from 3

select
m.id Ticket,
CONVERT(VARCHAR(10), m.msg_time, 103) + ' '  + convert(VARCHAR(8), m.msg_time, 14) [Data/Hora],
'Pública' [Ação é Pública? (Pública/Interna)],
case when u.ref_id = '1' then '454' else u.ref_id end as Gerador,
m.msg_body Descricao,
ROW_NUMBER() OVER (PARTITION BY m.id ORDER BY m.id asc) AS 'Acao'
from service_req_msg m
left join sysaid_user u on m.from_user = u.user_name -- Gerador das Ações
where m.method not in('auto') and m.id in(42977)
order by id asc
  • Is there an order to do this? How is it inserted? Is there any logic you haven’t passed on to us to understand?

  • @Virgilionovic, opa friend. I edited the question. Thank you

1 answer

1


It does not make sense to use the same column in the PARTITION BY clause and in ORDER BY. What is done is to use a set of columns to define the group (partitioning) and another set of columns to define the sort within the group. Of course "column set" can be a single column or more than one column.

When using the same set of columns in the two clauses, the ordered result is not deterministic; that is, with each execution the result of rows can come in different order.

how do I perform a counter on the sql server from a certain number.

Use an expression like:

 ...
 2 + ROW_NUMBER() OVER (PARTITION BY m.id ORDER BY ____ asc),
 ...
  • very obg. It worked fine

Browser other questions tagged

You are not signed in. Login or sign up in order to post.