Две таблицы, отдельный номер лицензии для возврата - PullRequest
1 голос
/ 07 января 2020

Имеют две таблицы, которые отображают информацию о владельце зарегистрированных собак; одна для 2018 года и другая для 2019 года. Каждая таблица имеет одинаковые столбцы, имена и т. д. c.

Мне нужно перечислить только одну полную запись по номеру лицензии. Например, собака, возможно, не была зарегистрирована в 2019 году, но была зарегистрирована в 2018. Поэтому мне нужно перечислить запись 2018 года, если она не содержится в таблице 2019. Если есть две записи (одна для 2018 года, а другая для 2019 года), я хочу, чтобы в списке была только запись 2019.

Union не работает именно потому, что номера "RegNumber" или номера тега собаки меняются из года в год. ; не говоря уже о возможных изменениях адреса, et c. Я пробовал комбинацию объединения, пересечения и исключения, и, похоже, ничего не работает должным образом. Любые идеи?

SELECT [License Number] AS [LicenseNumber], [Last Name] AS [LastName], [First Name] AS [Firstname], [Street Name] AS [StreetName], [Address2], [City], [State], [Zip], [Phone], '' AS [Email], [Reg Number] AS [RegNumber], [Dog Name] AS [DogName], [Dog Breed] AS [Breed], [Purchased] AS [Year], [Sex], [Altered], [Color], [Vet] AS [Veterinarian], [RabieTag] AS [RabiesTagNumber], [RabiesTag_Exp] AS [RabiesTagExpiration], [Dog Number] AS [OwnerID], [Reg Number] AS [TagNumber]
FROM [dbo].[Dog_Info_2019]
WHERE Flag is not null

UNION

SELECT [License Number] AS [LicenseNumber], [Last Name] AS [LastName], [First Name] AS [Firstname], [Street Name] AS [StreetName], [Address2], [City], [State], [Zip], [Phone], '' AS [Email], [Reg Number] AS [RegNumber], [Dog Name] AS [DogName], [Dog Breed] AS [Breed], [Purchased] AS [Year], [Sex], [Altered], [Color], [Vet] AS [Veterinarian], [RabieTag] AS [RabiesTagNumber], [RabiesTag_Exp] AS [RabiesTagExpiration], [Dog Number] AS [OwnerID], [Reg Number] AS [TagNumber]
FROM [dbo].[Dog_Info_2018] 
WHERE Flag is not null

ORDER BY [LicenseNumber]

Когда я выполняю вышеупомянутый запрос, записи 2018 и 2019 отображаются в общей сложности 22569 записей; 11176 строк в таблице 2018 и 11176 строк в таблице 2019.

Я даже пробовал NOT IN, но в этом списке перечислены только записи, которых нет ни в одной таблице, ни в другой.

Спасибо ..

Ответы [ 5 ]

1 голос
/ 08 января 2020

Я протестировал скрипт SQL ниже с некоторыми фиктивными данными, которые я создал, и это сработало. Я также создал представление. Я использовал UNION ALL для извлечения всех данных, а затем использовал оконную функцию для фильтрации дубликатов во внешнем WHERE. Я разделил по LicenseNumber, так как он уникален для животного.

Это не самый красивый, но он получит необходимые данные, пока вы не найдете более чистое решение.

SELECT LicenseYear
, [License Number] AS [LicenseNumber], [Last Name] AS [LastName], [First Name] AS 
[Firstname], [Street Name] AS [StreetName], [Address2], [City], [State], [Zip], 
[Phone], '' AS [Email], [Reg Number] AS [RegNumber], [Dog Name] AS [DogName], [Dog 
Breed] AS [Breed], [Purchased] AS [Year], [Sex], [Altered], [Color], [Vet] AS 
[Veterinarian], [RabieTag] AS [RabiesTagNumber], [RabiesTag_Exp] AS 
[RabiesTagExpiration], [Dog Number] AS [OwnerID], [Reg Number] AS [TagNumber]

FROM  (
      SELECT ROW_NUMBER() OVER (PARTITION BY LicenseNumber ORDER BY LicenseNumber, LicenseYear DESC ) AS 'RowNum'
      , *
      FROM  (
            --SELECT 2020 AS 'LicenseYear'
            --, [License Number] AS [LicenseNumber], [Last Name] AS [LastName], [First Name] AS [Firstname], [Street Name] AS [StreetName], [Address2], [City], [State], [Zip], [Phone], '' AS [Email], [Reg Number] AS [RegNumber], [Dog Name] AS [DogName], [Dog Breed] AS [Breed], [Purchased] AS [Year], [Sex], [Altered], [Color], [Vet] AS [Veterinarian], [RabieTag] AS [RabiesTagNumber], [RabiesTag_Exp] AS [RabiesTagExpiration], [Dog Number] AS [OwnerID], [Reg Number] AS [TagNumber]
            --FROM [dbo].[Dog_Info_2020]
            --WHERE Flag is not null

            --UNION ALL

            SELECT 2019 AS 'LicenseYear'
            , [License Number] AS [LicenseNumber], [Last Name] AS [LastName], [First Name] AS [Firstname], [Street Name] AS [StreetName], [Address2], [City], [State], [Zip], [Phone], '' AS [Email], [Reg Number] AS [RegNumber], [Dog Name] AS [DogName], [Dog Breed] AS [Breed], [Purchased] AS [Year], [Sex], [Altered], [Color], [Vet] AS [Veterinarian], [RabieTag] AS [RabiesTagNumber], [RabiesTag_Exp] AS [RabiesTagExpiration], [Dog Number] AS [OwnerID], [Reg Number] AS [TagNumber]
            FROM [dbo].[Dog_Info_2019]
            WHERE Flag is not null

            UNION ALL

            SELECT 2018 AS 'LicenseYear'
            , [License Number] AS [LicenseNumber], [Last Name] AS [LastName], [First Name] AS [Firstname], [Street Name] AS [StreetName], [Address2], [City], [State], [Zip], [Phone], '' AS [Email], [Reg Number] AS [RegNumber], [Dog Name] AS [DogName], [Dog Breed] AS [Breed], [Purchased] AS [Year], [Sex], [Altered], [Color], [Vet] AS [Veterinarian], [RabieTag] AS [RabiesTagNumber], [RabiesTag_Exp] AS [RabiesTagExpiration], [Dog Number] AS [OwnerID], [Reg Number] AS [TagNumber]
            FROM [dbo].[Dog_Info_2018] 
            WHERE Flag is not null
            ) Data
     ) Data 
WHERE RowNum = 1
0 голосов
/ 08 января 2020

Спасибо всем за ваш ответ; они очень помогли.

Мы смогли заставить что-то работать, используя следующий запрос для создания представления, которое работает правильно.

SELECT DISTINCT 
         [Year] AS [LicenseYear], [License Number], [Last Name] AS [LastName], [First Name] AS [Firstname], [Street Name] AS [StreetName], [Address2], [City], [State], [Zip], [Phone], '' AS [Email], [Reg Number] AS [RegNumber], [Dog Name], [Dog reed], [Purchased], [Sex], [Altered], [Color], [Vet], [RabieTag], [RabiesTag_Exp], [Dog Number] AS [OwnerID], [Reg Number] AS [TagNumber]
FROM [dbo].[Dog_Info_2019]
WHERE [Flag] IS NOT NULL
UNION
SELECT DISTINCT 
         [Year] AS [LicenseYear], [License Number], [Last Name] AS [LastName], [First Name] AS [Firstname], [Street Name] AS [StreetName], [Address2], [City], [State], [Zip], [Phone], '' AS [Email], [Reg Number] AS [RegNumber], [Dog Name], [Dog Breed], [Purchased], [Sex], [Altered], [Color], [Vet], [RabieTag], [RabiesTag_Exp], [Dog Number] AS [OwnerID], [Reg Number] AS [TagNumber]
FROM [dbo].[Dog_Info_2018]
WHERE [Flag] IS NOT NULL 
         AND [Dog_Info_2018].[License Number] NOT IN 
         (SELECT [License Number] FROM [Dog_Info_2019])
0 голосов
/ 07 января 2020

Согласно вашим комментариям, License Number является уникальным идентификатором, поэтому вы можете сделать это с помощью FULL JOIN.

SELECT COALESCE(di1.[License Number], di2.[License Number]) AS [LicenseNumber], ...
FROM Dog_Info_2019 di1
FULL JOIN Dog_Info_2018 di2 ON di2.[License Number] = di1.[License Number] AND di2.[Flag] IS NOT NULL AND di1.[Flag] IS NOT NULL
WHERE COALESCE(di1.[Flag], di2.[Flag]) IS NOT NULL 
ORDER BY COALESCE(di1.[License Number], di2.[License Number])

Если вы также можете рассчитывать на Flag Чтобы сопоставить столбец для обеих записей, вы можете упростить JOIN следующим образом:

FULL JOIN Dog_Info_2018 di2 ON di2.[License Number] = di1.[License Number] AND di2.[Flag] = di1.[Flag]
0 голосов
/ 08 января 2020

Я предположил, что Year является целым числом в вашем примере. Попробуйте этот код.


SELECT [LicenseNumber], MAX([Year]) AS [Year]
INTO #temp
FROM    (
    SELECT [License Number] AS [LicenseNumber], [Purchased] AS [Year]
    FROM [dbo].[Dog_Info_2019]
    WHERE Flag is not null
    UNION
    SELECT [License Number] AS [LicenseNumber], [Purchased] AS [Year]
    FROM [dbo].[Dog_Info_2018] 
    WHERE Flag is not null
)
GROUP BY [LicenseNumber]

SELECT a.*
FROM (
    SELECT [License Number] AS [LicenseNumber], [Last Name] AS [LastName], [First Name] AS [Firstname], [Street Name] AS [StreetName], [Address2], [City], [State], [Zip], [Phone], '' AS [Email], [Reg Number] AS [RegNumber], [Dog Name] AS [DogName], [Dog Breed] AS [Breed], [Purchased] AS [Year], [Sex], [Altered], [Color], [Vet] AS [Veterinarian], [RabieTag] AS [RabiesTagNumber], [RabiesTag_Exp] AS [RabiesTagExpiration], [Dog Number] AS [OwnerID], [Reg Number] AS [TagNumber]
FROM [dbo].[Dog_Info_2019]
WHERE Flag is not null

UNION

SELECT [License Number] AS [LicenseNumber], [Last Name] AS [LastName], [First Name] AS [Firstname], [Street Name] AS [StreetName], [Address2], [City], [State], [Zip], [Phone], '' AS [Email], [Reg Number] AS [RegNumber], [Dog Name] AS [DogName], [Dog Breed] AS [Breed], [Purchased] AS [Year], [Sex], [Altered], [Color], [Vet] AS [Veterinarian], [RabieTag] AS [RabiesTagNumber], [RabiesTag_Exp] AS [RabiesTagExpiration], [Dog Number] AS [OwnerID], [Reg Number] AS [TagNumber]
FROM [dbo].[Dog_Info_2018] 
WHERE Flag is not null
) a
INNER JOIN #temp b
 ON a.[LicenseNumber] = b.[LicenseNumber]
 AND a.[Year] = b.[Year]

0 голосов
/ 07 января 2020

Попробуйте это:

SELECT TOP 1 * FROM (

    SELECT [License Number] AS [LicenseNumber], [Last Name] AS [LastName], [First Name] AS [Firstname], [Street Name] AS [StreetName], [Address2], [City], [State], [Zip], [Phone], '' AS [Email], [Reg Number] AS [RegNumber], [Dog Name] AS [DogName], [Dog Breed] AS [Breed], [Purchased] AS [Year], [Sex], [Altered], [Color], [Vet] AS [Veterinarian], [RabieTag] AS [RabiesTagNumber], [RabiesTag_Exp] AS [RabiesTagExpiration], [Dog Number] AS [OwnerID], [Reg Number] AS [TagNumber]
    FROM [dbo].[Dog_Info_2019]
    WHERE Flag is not null
    UNION ALL
    SELECT [License Number] AS [LicenseNumber], [Last Name] AS [LastName], [First Name] AS [Firstname], [Street Name] AS [StreetName], [Address2], [City], [State], [Zip], [Phone], '' AS [Email], [Reg Number] AS [RegNumber], [Dog Name] AS [DogName], [Dog Breed] AS [Breed], [Purchased] AS [Year], [Sex], [Altered], [Color], [Vet] AS [Veterinarian], [RabieTag] AS [RabiesTagNumber], [RabiesTag_Exp] AS [RabiesTagExpiration], [Dog Number] AS [OwnerID], [Reg Number] AS [TagNumber]
    FROM [dbo].[Dog_Info_2018] 
    WHERE Flag is not null

) AS Registrations
ORDER BY 
    Registrations.LicenseNumber;

Если вам нужна самая последняя запись, то лучше включить дату (DES C) в ваш род.

...