2
I have a attendance list table, where I need a list identifying who was present:
Table structure:
create table lista_presenca_usuario
(
   id int identity(1,1),
   usuarioId int,
   dia int,
   turno int,
   presente int
)
insert into lista_presenca_usuario 
(usuarioId, dia, turno, presente)
values
 ( 10,1, 1, 1)
,( 10,1, 2, 0)
,( 10,2, 1, 1)
,( 10,2, 2, 1)
,( 20,1, 1, 1)
,( 20,1, 2, 1)
,( 20,2, 1, 1)
,( 20,2, 2, 1)
Approach Nº 1:
I make a time table, and update the lines:
select 
  usuarioId
  ,cast('' as varchar(20)) as primeiro_dia_manha
  ,cast('' as varchar(20)) as primeiro_dia_tarde
  ,cast('' as varchar(20)) as segundo_dia_manha
  ,cast('' as varchar(20)) as segundo_dia_tarde
 into #tmpDadosExport3
 from lista_presenca_usuario
 group by usuarioId
update t
  set t.primeiro_dia_manha = case when lpu.presente = 0 then 'ausente' else 'presente' end
 from #tmpDadosExport3 t
 join lista_presenca_usuario lpu(nolock) on t.usuarioId = lpu.usuarioId
 and lpu.turno = 1 and lpu.Dia = 1 
update t
  set t.primeiro_dia_tarde = case when lpu.presente = 0 then 'ausente' else 'presente' end
 from #tmpDadosExport3 t
 join lista_presenca_usuario lpu(nolock) on t.usuarioId = lpu.usuarioId
 and lpu.turno = 2 and lpu.Dia = 1 
update t
  set t.segundo_dia_manha = case when lpu.presente = 0 then 'ausente' else 'presente' end
 from #tmpDadosExport3 t
 join lista_presenca_usuario lpu(nolock) on t.usuarioId = lpu.usuarioId
 and lpu.turno = 1 and lpu.Dia = 2
update t
  set t.segundo_dia_tarde = case when lpu.presente = 0 then 'ausente' else 'presente' end
 from #tmpDadosExport3 t
join lista_presenca_usuario lpu(nolock) on t.usuarioId = lpu.usuarioId
 and lpu.turno = 2 and lpu.Dia = 2
It works, but it’s expensive, I am trying now this query
SELECT usuarioid, x.primeiro_dia_manha, x.primeiro_dia_tarde FROM lista_presenca_usuario y
inner join (
  select
   id
   ,case when turno = 1 and Dia = 1 then
                    case when presente = 0 then 'ausente' else 'presente' end
                    end AS primeiro_dia_manha
  ,case when turno = 2 and Dia = 1 then
                    case when presente = 0 then 'ausente' else 'presente' end
                    end AS primeiro_dia_tarde
  from lista_presenca_usuario
)x on x.id = y.id
group by usuarioid, x.primeiro_dia_manha, x.primeiro_dia_tarde
but unfortunately, it returns duplicated lines, even though I do a group by.
Expected result:
usuarioId|primeiro_dia_manha|primeiro_dia_tarde
10       |presente          |ausente           
20       |presente          |presente          
The result that is coming:
usuarioId|primeiro_dia_manha|primeiro_dia_tarde
10       |presente          |Null           
20       |Null              |presente          
10       |presente          |Null          
20       |Null              |presente             
I made a sql fiddle to illustrate: http://sqlfiddle.com/#! 18/fdb69/7