Отключить несколько столбцов в ряды - PullRequest
0 голосов
/ 27 марта 2019

Я работаю над отчетом журнала аудита и пользователями, которым нравится видеть исходные значения, которые были вставлены при создании записи, но, к сожалению, наши журналы аудита просто сохраняют запись как «Запись создана», но запись не делает содержат вставленные значения. Смотрите скриншот ниже:

enter image description here

Итак, все, что я изначально знаю, это то, что этот сертификат был вставлен 14.03.2009 - не идеально для того, что я пытаюсь сделать, но это то, что есть.

Меня интересует поиск вставленных значений для четырех столбцов из этой таблицы:

  • CertificationTypeID
  • CertificateIdentifier
  • StateCertificationIssued
  • DateCertificationIssued

Используя журналы аудита и таблицу сертификации, я могу воссоздать исходные значения, которые были при вставке записи, но каждый из столбцов таблицы сертификации представлен четырьмя столбцами в моем наборе записей журнала аудита:

  • OriginalValue
  • FieldName
  • ActionDate
  • RecordCreation

enter image description here

То, что я надеюсь сделать, - это развернуть (или перекрестно применить) столбцы, содержащие записи исходного значения, в строки, которые будут представлять каждый столбец, который был вставлен.

enter image description here

Например, первые четыре столбца для исходных записей - CT_OriginalValue, CT_FieldName, CT_ActionDate и CT_RecordCreation. Мне нужно, чтобы они превратились в четыре строки, которые заменили бы первую «Созданную запись», которая не содержала никакой информации.

В идеале - CT_FieldName и CT_RecordCreation должны быть конкатенированы и развернуты в строку и попадать в столбец ColumnName, CT_OriginalValue будет отключен в столбце NewValue, CT_ActionDate будет отключен для DateChanged.

Я пытался UNPIVOT, но мне не очень повезло, и я видел CROSS APPLY, использованный в этих ситуациях, но я не могу понять, как применить к этой ситуации.

Пример данных ниже:

CREATE TABLE #AuditLogCustomerCert
    (
        ColumnName NVARCHAR (128) ,
        OldValue VARCHAR (MAX) ,
        NewValue VARCHAR (MAX) ,
        DateChanged DATETIME2 (7) ,
        ActionType CHAR (1) ,
        AuditLogPK VARCHAR (400) ,
        CT_OriginalValue VARCHAR (200) ,
        CT_FieldName VARCHAR (19) ,
        CT_ActionDate DATETIME2 (7) ,
        CT_RecordCreation VARCHAR (14) ,
        CI_OriginalValue VARCHAR (MAX) ,
        CI_FieldName VARCHAR (21) ,
        CI_ActionDate DATETIME2 (7) ,
        CI_RecordCreation VARCHAR (14) ,
        SCI_OriginalValue VARCHAR (MAX) ,
        SCI_FieldName VARCHAR (24) ,
        SCI_ActionDate DATETIME2 (7) ,
        SCI_RecordCreation VARCHAR (14) ,
        DCI_OriginalValue DATETIME ,
        DCI_FieldName VARCHAR (23) ,
        DCI_ActionDate DATETIME2 (7) ,
        DCI_RecordCreation VARCHAR (14)
    );
INSERT INTO #AuditLogCustomerCert
VALUES ( N'Record Created', NULL, NULL, N'2019-03-14T10:55:06.0014212', 'I', '<CustomerCertificationID=327857>', 'Hunter Safety Certificate', 'CertificationTypeID', N'2019-03-14T10:55:06.0014212', 'Record Created', 'IA299038794' ,
         'CertificateIdentifier' , N'2019-03-14T10:55:06.0014212', 'Record Created', '66', 'StateCertificationIssued', N'2019-03-14T10:55:06.0014212', 'Record Created', N'2019-02-28T00:00:00', 'DateCertificationIssued' ,
         N'2019-03-14T10:55:06.0014212' , 'Record Created' ) ,
       ( N'StateCertificationIssued', '66', 'UA', N'2019-03-14T13:04:45.1401862', 'U', '<CustomerCertificationID=327857>', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL ) ,
       ( N'createDate', 'Mar 14 2019 10:55AM', 'Mar 19 2019  1:52PM', N'2019-03-19T13:52:29.5221885', 'U', '<CustomerCertificationID=327857>', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL ) ,
       ( N'createDate', 'Mar 19 2019  1:52PM', 'Mar 22 2019 10:43AM', N'2019-03-22T10:43:42.1068855', 'U', '<CustomerCertificationID=327857>', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL ) ,
       ( N'createDate', 'Mar 22 2019 10:43AM', 'Mar 22 2019  2:38PM', N'2019-03-22T14:38:57.5266904', 'U', '<CustomerCertificationID=327857>', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL ) ,
       ( N'StateCertificationIssued', 'UA', 'NJ', N'2019-03-26T11:25:28.9015254', 'U', '<CustomerCertificationID=327857>', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL ) ,
       ( N'CountryCertificationIssued', 'Gabon ', 'United States ', N'2019-03-26T11:25:28.9015254', 'U', '<CustomerCertificationID=327857>', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL ) ,
       ( N'createDate', 'Mar 22 2019  2:38PM', 'Mar 26 2019  2:23PM', N'2019-03-26T14:23:27.8660009', 'U', '<CustomerCertificationID=327857>', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL ) ,
       ( N'Record Created', NULL, NULL, N'2019-03-26T10:30:19.3982917', 'I', '<CustomerCertificationID=327877>', 'Boater Safety Certificate', 'CertificationTypeID', N'2019-03-26T10:30:19.3982917', 'Record Created', 'IAC031900001' ,
         'CertificateIdentifier' , N'2019-03-26T10:30:19.3982917', 'Record Created', 'IA', 'StateCertificationIssued', N'2019-03-26T10:30:19.3982917', 'Record Created', N'2019-03-07T00:00:00', 'DateCertificationIssued' ,
         N'2019-03-26T10:30:19.3982917' , 'Record Created' ) ,
       ( N'CertificateIdentifier', 'IAC031900001', 'IAC031900002', N'2019-03-26T22:02:21.3292077', 'U', '<CustomerCertificationID=327877>', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL ) ,
       ( N'Record Created', NULL, NULL, N'2019-03-26T22:12:29.4201277', 'I', '<CustomerCertificationID=327887>', 'Temporarily Disabled', 'CertificationTypeID', N'2019-03-26T22:12:29.4201277', 'Record Created', '', 'CertificateIdentifier' ,
         N'2019-03-26T22:12:29.4201277' , 'Record Created', 'IA', 'StateCertificationIssued', N'2019-03-26T22:12:29.4201277', 'Record Created', N'2019-03-13T00:00:00', 'DateCertificationIssued', N'2019-03-26T22:12:29.4201277' ,
         'Record Created' ) ,
       ( N'CertificateIdentifier', '', 'IAC9985478', N'2019-03-26T22:12:47.3471693', 'U', '<CustomerCertificationID=327887>', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL );

SELECT * FROM #AuditLogCustomerCert;

--SELECT ColumnName, up.NewValue

--FROM (

--SELECT CONCAT(ColumnName,'-',CT_FieldName), CT_OriginalValue
--FROM #AuditLogCustomerCert
--) AS cp
--UNPIVOT
--( 
--NewValue FOR NewValue IN ( CT_OriginalValue )) AS up;

DROP TABLE IF EXISTS #AuditLogCustomerCert;

1 Ответ

1 голос
/ 28 марта 2019

Как насчет "UNPIVOT", который вам нужен, и "UNION ALL" с другими? И мне было плевать на порядок строк.

IF OBJECT_ID('tempdb..#AuditLogCustomerCert') IS NOT NULL
  DROP TABLE #AuditLogCustomerCert;

CREATE TABLE #AuditLogCustomerCert(
  ColumnName NVARCHAR (128) ,
  OldValue VARCHAR (MAX) ,
  NewValue VARCHAR (MAX) ,
  DateChanged DATETIME2 (7) ,
  ActionType CHAR (1) ,
  AuditLogPK VARCHAR (400) ,
  CT_OriginalValue VARCHAR (200) ,
  CT_FieldName VARCHAR (19) ,
  CT_ActionDate DATETIME2 (7) ,
  CT_RecordCreation VARCHAR (14) ,
  CI_OriginalValue VARCHAR (MAX) ,
  CI_FieldName VARCHAR (21) ,
  CI_ActionDate DATETIME2 (7) ,
  CI_RecordCreation VARCHAR (14) ,
  SCI_OriginalValue VARCHAR (MAX) ,
  SCI_FieldName VARCHAR (24) ,
  SCI_ActionDate DATETIME2 (7) ,
  SCI_RecordCreation VARCHAR (14) ,
  DCI_OriginalValue DATETIME ,
  DCI_FieldName VARCHAR (23) ,
  DCI_ActionDate DATETIME2 (7) ,
  DCI_RecordCreation VARCHAR (14)
);
INSERT #AuditLogCustomerCert
VALUES (N'Record Created', NULL, NULL, N'2019-03-14T10:55:06.0014212', 'I',
        '<CustomerCertificationID=327857>', 'Hunter Safety Certificate',
        'CertificationTypeID', N'2019-03-14T10:55:06.0014212',
        'Record Created', 'IA299038794', 'CertificateIdentifier',
        N'2019-03-14T10:55:06.0014212', 'Record Created', '66',
        'StateCertificationIssued', N'2019-03-14T10:55:06.0014212',
        'Record Created', N'2019-02-28T00:00:00', 'DateCertificationIssued',
        N'2019-03-14T10:55:06.0014212', 'Record Created'),
       (N'StateCertificationIssued', '66', 'UA', N'2019-03-14T13:04:45.1401862',
        'U', '<CustomerCertificationID=327857>', NULL, NULL, NULL, NULL, NULL,
        NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL) ,
       (N'createDate', 'Mar 14 2019 10:55AM', 'Mar 19 2019  1:52PM',
        N'2019-03-19T13:52:29.5221885', 'U', '<CustomerCertificationID=327857>',
        NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
        NULL, NULL, NULL, NULL),
       (N'createDate', 'Mar 19 2019  1:52PM', 'Mar 22 2019 10:43AM',
        N'2019-03-22T10:43:42.1068855', 'U', '<CustomerCertificationID=327857>',
        NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
        NULL, NULL, NULL, NULL),
       (N'createDate', 'Mar 22 2019 10:43AM', 'Mar 22 2019  2:38PM',
        N'2019-03-22T14:38:57.5266904', 'U', '<CustomerCertificationID=327857>',
        NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
        NULL, NULL, NULL, NULL),
       (N'StateCertificationIssued', 'UA', 'NJ', N'2019-03-26T11:25:28.9015254',
        'U', '<CustomerCertificationID=327857>', NULL, NULL, NULL, NULL, NULL,
        NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL),
       (N'CountryCertificationIssued', 'Gabon ', 'United States ',
        N'2019-03-26T11:25:28.9015254', 'U', '<CustomerCertificationID=327857>',
        NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
        NULL, NULL, NULL, NULL),
       (N'createDate', 'Mar 22 2019  2:38PM', 'Mar 26 2019  2:23PM',
        N'2019-03-26T14:23:27.8660009', 'U', '<CustomerCertificationID=327857>',
        NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
        NULL, NULL, NULL, NULL),
       (N'Record Created', NULL, NULL, N'2019-03-26T10:30:19.3982917', 'I',
        '<CustomerCertificationID=327877>', 'Boater Safety Certificate',
        'CertificationTypeID', N'2019-03-26T10:30:19.3982917', 'Record Created',
        'IAC031900001', 'CertificateIdentifier' , N'2019-03-26T10:30:19.3982917',
        'Record Created', 'IA', 'StateCertificationIssued',
        N'2019-03-26T10:30:19.3982917', 'Record Created', N'2019-03-07T00:00:00',
        'DateCertificationIssued', N'2019-03-26T10:30:19.3982917',
        'Record Created'),
       (N'CertificateIdentifier', 'IAC031900001', 'IAC031900002',
        N'2019-03-26T22:02:21.3292077', 'U', '<CustomerCertificationID=327877>',
        NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
        NULL, NULL, NULL, NULL),
       (N'Record Created', NULL, NULL, N'2019-03-26T22:12:29.4201277', 'I',
        '<CustomerCertificationID=327887>', 'Temporarily Disabled',
        'CertificationTypeID', N'2019-03-26T22:12:29.4201277', 'Record Created',
        '', 'CertificateIdentifier', N'2019-03-26T22:12:29.4201277',
        'Record Created', 'IA', 'StateCertificationIssued',
        N'2019-03-26T22:12:29.4201277', 'Record Created', N'2019-03-13T00:00:00',
        'DateCertificationIssued', N'2019-03-26T22:12:29.4201277',
        'Record Created' ) ,
       (N'CertificateIdentifier', '', 'IAC9985478', N'2019-03-26T22:12:47.3471693',
        'U', '<CustomerCertificationID=327887>', NULL, NULL, NULL, NULL, NULL,
        NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);

SELECT
  ColumnName,
  OldValue,
  NewValue,
  DateChanged,
  ActionType,
  AuditLogPK
FROM #AuditLogCustomerCert
WHERE ColumnName != 'Record Created'
UNION ALL
SELECT
  CASE ColumnName
    WHEN 'CT_OriginalValue' THEN 'Record Created - CertificationTypeID'
    WHEN 'CI_OriginalValue' THEN 'Record Created - CertificateIdentifier'
    WHEN 'SCI_OriginalValue' THEN 'Record Created - StateCertificationIssued'
    WHEN 'DCI_OriginalValue' THEN 'Record Created - DateCertificationIssued'
  END,
  NULL,
  NewValue,
  DateChanged,
  ActionType,
  AuditLogPK
FROM (
  SELECT
    DateChanged,
    ActionType,
    AuditLogPK,
    CAST(CT_OriginalValue AS NVARCHAR(MAX)) CT_OriginalValue,
    CAST(CI_OriginalValue AS NVARCHAR(MAX)) CI_OriginalValue,
    CAST(SCI_OriginalValue AS NVARCHAR(MAX)) SCI_OriginalValue,
    CAST(DCI_OriginalValue AS NVARCHAR(MAX)) DCI_OriginalValue
  FROM #AuditLogCustomerCert
  WHERE ColumnName = 'Record Created'
) AS t
UNPIVOT (
  NewValue
  FOR ColumnName
  IN (CT_OriginalValue, CI_OriginalValue, SCI_OriginalValue, DCI_OriginalValue)
) AS unp;

Выход:

+-------------------------------------------+---------------------+---------------------------+---------------------+------------+----------------------------------+
|                ColumnName                 |      OldValue       |         NewValue          |     DateChanged     | ActionType |            AuditLogPK            |
+-------------------------------------------+---------------------+---------------------------+---------------------+------------+----------------------------------+
| StateCertificationIssued                  | 66                  | UA                        | 14/03/2019 13:04:45 | U          | <CustomerCertificationID=327857> |
| createDate                                | Mar 14 2019 10:55AM | Mar 19 2019  1:52PM       | 19/03/2019 13:52:29 | U          | <CustomerCertificationID=327857> |
| createDate                                | Mar 19 2019  1:52PM | Mar 22 2019 10:43AM       | 22/03/2019 10:43:42 | U          | <CustomerCertificationID=327857> |
| createDate                                | Mar 22 2019 10:43AM | Mar 22 2019  2:38PM       | 22/03/2019 14:38:57 | U          | <CustomerCertificationID=327857> |
| StateCertificationIssued                  | UA                  | NJ                        | 26/03/2019 11:25:28 | U          | <CustomerCertificationID=327857> |
| CountryCertificationIssued                | Gabon               | United States             | 26/03/2019 11:25:28 | U          | <CustomerCertificationID=327857> |
| createDate                                | Mar 22 2019  2:38PM | Mar 26 2019  2:23PM       | 26/03/2019 14:23:27 | U          | <CustomerCertificationID=327857> |
| CertificateIdentifier                     | IAC031900001        | IAC031900002              | 26/03/2019 22:02:21 | U          | <CustomerCertificationID=327877> |
| CertificateIdentifier                     |                     | IAC9985478                | 26/03/2019 22:12:47 | U          | <CustomerCertificationID=327887> |
| Record Created - CertificationTypeID      |                     | Hunter Safety Certificate | 14/03/2019 10:55:06 | I          | <CustomerCertificationID=327857> |
| Record Created - CertificateIdentifier    |                     | IA299038794               | 14/03/2019 10:55:06 | I          | <CustomerCertificationID=327857> |
| Record Created - StateCertificationIssued |                     | 66                        | 14/03/2019 10:55:06 | I          | <CustomerCertificationID=327857> |
| Record Created - DateCertificationIssued  |                     | Feb 28 2019 12:00AM       | 14/03/2019 10:55:06 | I          | <CustomerCertificationID=327857> |
| Record Created - CertificationTypeID      |                     | Boater Safety Certificate | 26/03/2019 10:30:19 | I          | <CustomerCertificationID=327877> |
| Record Created - CertificateIdentifier    |                     | IAC031900001              | 26/03/2019 10:30:19 | I          | <CustomerCertificationID=327877> |
| Record Created - StateCertificationIssued |                     | IA                        | 26/03/2019 10:30:19 | I          | <CustomerCertificationID=327877> |
| Record Created - DateCertificationIssued  |                     | Mar  7 2019 12:00AM       | 26/03/2019 10:30:19 | I          | <CustomerCertificationID=327877> |
| Record Created - CertificationTypeID      |                     | Temporarily Disabled      | 26/03/2019 22:12:29 | I          | <CustomerCertificationID=327887> |
| Record Created - CertificateIdentifier    |                     |                           | 26/03/2019 22:12:29 | I          | <CustomerCertificationID=327887> |
| Record Created - StateCertificationIssued |                     | IA                        | 26/03/2019 22:12:29 | I          | <CustomerCertificationID=327887> |
| Record Created - DateCertificationIssued  |                     | Mar 13 2019 12:00AM       | 26/03/2019 22:12:29 | I          | <CustomerCertificationID=327887> |
+-------------------------------------------+---------------------+---------------------------+---------------------+------------+----------------------------------+

Тестирование онлайн с db <> fiddle .

...