SQL source code

I have 3 tables. In one table there are all people [Pat], each with a unique one [PatId]. The second table contains all the information about the insurance company [Ins], each of which is unique [InsId]. The third table contains patient insurance information [PatIns]. In the table [PatIns], some patients (also [PatId]) have secondary or third insurance, and it is indicated as [InsType]1, 2 or 3. I need an SQL query that will not only join 3 tables, but also return data when the patient has secondary or third insurance. So far, I:

SELECT * 

FROM [XEREX_TEST].[dbo].[xrxPat], 

[XEREX_TEST].[dbo].[xrxIns],

[XEREX_TEST].[dbo].[xrxPatIns]

[XEREX_TEST].[dbo].[xrxPatIns] AS INS2,

[XEREX_TEST].[dbo].[xrxPatIns] AS INS3 

WHERE [xrxPat].[PatId]=[xrxPatIns].[PatId] 

AND [xrxPatIns].[PatId] = INS2.[PatId] 

AND [xrxPatIns].[PatId] = INS3.[PatId]

AND [xrxIns].[RecNo]=[xrxPatIns].[InsId] 

AND [xrxPatIns].[InsType]=1

AND INS2.[InsType]=2 

AND INS3.[InsType]=3;   

, 3 . INS2 / INS3, 1 . ?

+3
2

where, , .

SELECT
  *
FROM [XEREX_TEST].[dbo].[xrxPat]
INNER JOIN [XEREX_TEST].[dbo].[xrxIns]
    ON [xrxPat].[PatId] = [xrxIns].[PatId]
INNER JOIN [XEREX_TEST].[dbo].[xrxPatIns]
    ON [xrxIns].[RecNo] = [xrxPatIns].[InsId]
    AND [xrxPatIns].[InsType] = 1
LEFT JOIN [XEREX_TEST].[dbo].[xrxPatIns] AS INS2
    ON [xrxIns].[RecNo] = INS2.[PatId]
    AND INS2.[InsType] = 2
LEFT JOIN [XEREX_TEST].[dbo].[xrxPatIns] AS INS3
    ON [xrxIns].[RecNo] = INS3.[PatId]
    AND INS3.[InsType] = 3;
+2

JOIN . .

SELECT * 
FROM 
(SELECT * FROM [XEREX_TEST].[dbo].[xrxPatIns] WHERE [InsType]=1) AS INS1
LEFT JOIN
(SELECT * FROM [XEREX_TEST].[dbo].[xrxPatIns] WHERE [InsType]=2) AS INS2
ON INS1.[PatId] = INS2.[PatId]
LEFT JOIN
(SELECT * FROM [XEREX_TEST].[dbo].[xrxPatIns] WHERE [InsType]=3) AS INS3
ON INS1.[PatId] = INS3.[PatId]
JOIN
[XEREX_TEST].[dbo].[xrxPat]
ON [xrxPat].[PatId]=INS1.[PatId] 
JOIN
[XEREX_TEST].[dbo].[xrxIns]
ON [xrxIns].[RecNo]=INS1.[InsId] 
;   
0

Source: https://habr.com/ru/post/1729993/


All Articles