How to generate a counter within a select (SQL server)

Asked

Viewed 3,898 times

0

I need to make a select with a case, if the condition is true use a counter that will be a new column, otherwise the counter will be displayed without any change, but I’m not succeeding, I tried with the ROW_NUMBER function but it did not work, if anyone can help me I appreciate:

    declare @c int 
    set @c = 0
    select 
    (
         case when HR_ENTRADA > is null then
         (
             (ROW_NUMBER()over(order by HR_ENTRADA asc)+@c) 
         )
         else
         (
           @c
         )
        end
   )as FALTAS

    from TB_REGISTRO_PONTO

This query works, but if you fall into Else, this row_number tmb counter adds, and I don’t want that, I just want it to add if the condition is true.

  • Can put an example of the expected result?

  • It is a point control, the query is only to check if the employee has mark in the input time, regardless of what time he hit the input, IE, if in this column have no value (NULL) will be a foul, and the counter adds 1.

  • You could try changing your logic to: case when HR_ENTRADA is null then or need to have Else. It has better ways to count.

1 answer

0


I’m not sure I understand the question, but that’s what you want?

SELECT
    SUM(CASE WHEN {CONDIÇÃO VERDADEIRA} THEN 1 ELSE 0 END) AS FALTAS
FROM
    TB_REGISTRO_PONTO
  • SELECT
 SUM(CASE WHEN HR_ENTRADA is null THEN 1 ELSE 0 END) AS FALTAS
FROM
 TB_REGISTRO_PONTO Apply this solution of Paul

  • Simpler than I thought.

  • Thank you very much!!

Browser other questions tagged

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