How to get all the records of a table with maximum date?

1

I have two tables of which I have repeated values and what I want to obtain is the all value with maximum date of each table and that they do not repeat themselves and I do not know how to perform.

I have two tables one of them is A which has many fields but the one I need is the user code field but there are several records with the same user code and I'm interested in booting the maximum date, and then I have another table call B where is the user code, if it is written off and the date of creation and here I have the same problem as in table A.

This is the query.

SELECT        
    x.cod_paciente,
    x.cod_centro,
    x.gidenpac,
    CONVERT(varchar(35),c.des_Nombre) AS des_nombre,
    CONVERT(varchar(35),c.des_Apellido1) AS des_Apellido1,
    CONVERT(varchar(35), c.des_Apellido2) AS des_Apellido2,
    CONVERT(varchar(9), c.des_DocumentoIdentidad) AS des_DocumentoIdentidad ,
    c.Fec_Nacimiento,
    c.xti_Sexo,
    CAST(c.cod_tipoViaRes as varchar) + ' ' + CAST(des_DomicilioRes as varchar) + ' ' + CAST(C.des_NumeroRes as varchar) DOMICILIO,
    CONVERT(varchar(5), c.des_CodPostalRes) AS cod_DistritoPostal ,
    CONVERT(varchar(6), c.cod_PoblacionRes) AS cod_PoblacionRes, 
    CONVERT(varchar(2), d.cod_provincia) AS cod_Provincia,
    CONVERT(varchar(2), d.cod_Comunidad) AS cod_Comunidad,
    CONVERT(varchar(40), d.des_poblacion) AS des_poblacion,
    CONVERT(varchar(30), pr.des_provincia) AS des_provincia,
    CONVERT(varchar(40), co.des_Comunidad) AS des_Comunidad,
    CONVERT(varchar(15), c.des_telefono1) AS des_telefono1,
    CONVERT(varchar(15), c.des_telefono2) AS des_telefono2,
    CONVERT(varchar(15), c.des_telefono3) AS des_telefono3,
    CONVERT(varchar(100), c.des_EMAIL) AS des_EMAIL,
    P.IDSOCIEDAD,
    0 GINSPECC,
    NULL RTERC,
    NULL ETERC,
    @fecha as FECHAULTIMMOVIMIENTO,
    null as cod_telefono1,
    null as cod_telefono2,
    null as cod_telefono3,
    null as cod_domicilio,
    null as cod_apellido1,
    null as cod_apellido2,
    null as cod_madre,
    CONVERT(varchar(50), c.des_nafiliacion) AS des_nafiliacion ,
    CONVERT(varchar(50), c.des_ntarjeta) AS des_ntarjeta,
    c.cod_PacienteFMP,
    w.cod_Usuario
FROM DATOS_PACIENTES.DBO.TR_PACIENTE X with (nolock)
JOIN TR_Pacientes A  with (nolock)ON   X.GIDENPAC collate Modern_Spanish_CI_AS = A.GIDENPAC and
a.cod_centro =x.cod_centro collate Modern_Spanish_CI_AS
JOIN TD_Paciente c with (nolock) on a.cod_Paciente = c.cod_Paciente
LEFT JOIN TD_Poblacion d with (nolock) on c.cod_PoblacionRes = d.cod_poblacion
LEFT JOIN TC_Provincia pr with (nolock) on d.cod_provincia = pr.cod_provincia
LEFT JOIN TC_ComunidadAutonoma co with (nolock) on d.cod_Comunidad =co.cod_Comunidad
LEFT JOIN TH_CDM_AP_Pacientes v with(NOLOCK) ON c.cod_PacienteFMP = v.cod_PacienteFMP
                                             AND xti_Activo='1' 

LEFT JOIN TH_CDM_AP_RelacionUsuariosPacientes w WITH(NOLOCK) on v.cod_idPaciente = w.cod_IdPaciente
AND xti_Borrado='0'
AND xti_PacientePorDefecto='1'
INNER JOIN TH_CDM_AP_USUARIOS z WITH(NOLOCK) ON w.cod_Usuario =z.iduser
AND xti_baja='N'

LEFT JOIN (
                                  SELECT       A.IDPACIENTE,
                                               codCentroIdc, 
                                               A.IDHIS,
                                               B.CODIGOSNS,
                                               B.NUMTARJETASANITARIA,
                                               B.EMAIL,
                                               B.TELEFONO1,
                                               B.TELEFONO2,
                                               B.TELEFONO3,
                                               B.IDSOCIEDAD,
                                               B.FECHAULTIMMOVIMIENTO
                                  FROM [CASIOBDSQLLIS_Read].FMP.[dbo].[PacienteCentro] A with (nolock)
                                  JOIN [CASIOBDSQLLIS_Read].FMP.[dbo].[Paciente] B with (nolock) ON A.IDPACIENTE = B.ID
                                  JOIN [CASIOBDSQLLIS_Read].[FMP].[dbo].[Centro] C with (nolock) ON A.IDCENTRO = C.ID
                    ) P
ON  P.codCentroIdc collate Modern_Spanish_CI_AS = x.cod_centro AND
       X.GIDENPAC = p.IDHIS collate Modern_Spanish_CI_AS
WHERE
x.cod_paciente ='8001656' 

The problem of repeated data are in the following tables

TH_CDM_AP_RelacionUsuariosPacientes
[TH_CDM_AP_RelacionUsuariosPacientes](
    [cod_RelacionUsuarioPaciente] [numeric](10, 0) NOT NULL,
    [cod_Usuario] [numeric](10, 0) NOT NULL,
    [cod_TutorFMP] [numeric](10, 0) NOT NULL,
    [cod_IdPaciente] [numeric](10, 0) NOT NULL,
    [cod_TipoRelacion_Portal] [smallint] NOT NULL,
    [fec_Creacion] [datetime] NOT NULL,
    [cod_UsuarioDelegador] [numeric](10, 0) NULL,
    [cod_NivelAcceso_Portal] [smallint] NULL,
    [xti_Borrado] [numeric](1, 0) NULL,
    [fec_Borrado] [datetime] NULL,
    [xti_LecturaHC] [numeric](1, 0) NULL,
    [xti_EscrituraHC] [numeric](1, 0) NULL,
    [xti_PacientePorDefecto] [numeric](1, 0) NULL,
    [cod_CentroPorDefecto] [char](2) NULL,
    [cod_TipoPaciente_Portal] [nvarchar](10) NULL,
    [cod_Aseguradora] [nvarchar](10) NULL,
    [des_Aseguradora] [nvarchar](512) NULL,
    [cod_Poliza] [nvarchar](32) NULL,
    [fec_Modificacion] [datetime] NULL,
    [cod_CentroOrigen] [char](2) NULL,
    [fec_carga] [datetime] NOT NULL,
    [fec_ultmodificacion] [datetime] NOT NULL,
    [cod_CentroDWH] [nvarchar](10) NULL,
 CONSTRAINT [PK__TH_CDM_AP_RelacionUsuariosPacientes] PRIMARY KEY CLUSTERED 
(
    [cod_RelacionUsuarioPaciente] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

TH_CDM_AP_USUARIOS 
[TH_CDM_AP_USUARIOS](
    [FECHA_CREACION] [int] NULL,
    [FECHA_ULTIMA_MODIFICACION] [int] NULL,
    [ANYOMES] [int] NULL,
    [IDUSER] [numeric](10, 0) NOT NULL,
    [ISO] [nvarchar](5) NOT NULL,
    [LOGIN] [nvarchar](80) NOT NULL,
    [FULLNAME] [nvarchar](160) NOT NULL,
    [EMAIL] [nvarchar](80) NOT NULL,
    [DATECREATION] [datetime2](7) NOT NULL,
    [LASTCHANGE] [datetime2](7) NOT NULL,
    [NATIONALID] [nvarchar](40) NULL,
    [SEX] [numeric](1, 0) NULL,
    [MARRIAGE] [numeric](1, 0) NULL,
    [BIRTHDAY] [datetime2](7) NULL,
    [PLACEBIRTHDAY] [numeric](10, 0) NULL,
    [TIMEZONE] [nvarchar](128) NULL,
    [LOCKED] [numeric](1, 0) NULL,
    [DA] [numeric](1, 0) NULL,
    [PHONE] [nvarchar](20) NULL,
    [MOBILE] [nvarchar](20) NULL,
    [tipo_doc_identidad] [smallint] NULL,
    [photoIdMmedia] [nvarchar](512) NULL,
    [nombre] [nvarchar](512) NULL,
    [id_centro] [nvarchar](512) NULL,
    [condiciones_aceptadas] [nvarchar](512) NULL,
    [apellido2] [nvarchar](512) NULL,
    [apellido1] [nvarchar](512) NULL,
    [FECHA_CARGA] [datetime2](7) NULL,
    [FECHA_ULTIMA_ACTUALIZACION] [datetime2](7) NULL,
    [canal_alta] [char](2) NULL,
    [xti_baja] [char](1) NULL,
    [fec_baja] [datetime] NULL,
    [cod_MotivoBajaPortal] [int] NULL,
    [des_DESCRIPCIONBAJA] [nvarchar](512) NULL,
    [portal] [nvarchar](512) NULL,
    [cambiar_clave] [nvarchar](512) NULL,
    [sistema_origen] [nvarchar](512) NULL,
    [centro_origen] [char](2) NULL,
    [usuario_sistema_origen] [nvarchar](512) NULL,
    [tipo_usuario_sistema_origen] [nvarchar](512) NULL,
    [episodio_sistema_origen] [nvarchar](512) NULL,
    [doc_identidad_ss] [nvarchar](512) NULL,
    [PACIENTE] [numeric](1, 0) NULL,
    [SOCIOSANITARIO] [numeric](1, 0) NULL,
    [cod_CentroDWH] [nvarchar](10) NULL,
    [cod_CentroOrigenDWH] [nvarchar](512) NULL,
    [cod_CanalAltaDWH] [nvarchar](512) NULL,
 CONSTRAINT [PK_TH_CDM_AP_USUARIOS_IDUSER__] PRIMARY KEY CLUSTERED 
(
    [IDUSER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
    
asked by Borja Moreno 06.11.2018 в 16:02
source

2 answers

0

I think I have the solution to your problems. Assuming that the date is formatted to a format YYYYmmDD or format unix , it would be as simple as taking the maximum from table B and compare it with table A.

Although I would appreciate it if you put a screenshot with the data to make us better at the idea, sometimes the fact that there are images can make things easier.

SELECT * FROM TABLA_A
where AUD_FH_CREACION = (SELECT MAX(AUD_FH_CREACION) FROM TABLA_B)

Yes, what you want is to take values that have a specific condition, tell it and develop it (but you would have to use connectors and they could give null values).

    
answered by 06.11.2018 в 17:16
-1

To obtain the non-repeating values of the tables you use, the outer join and that select group the field you want not to repeat.

For better reference I recommend this image.

    
answered by 06.11.2018 в 16:40