Используя существующий оператор SQL, мне нужно дублировать строки, если значение в [Выполненное действие] равно «Просмотреть предыдущие действия».
«Просмотреть предыдущие действия» означает вернуться ко всем действиям, которые Участник дела получил для этого дела. По сути, каждая [Категория нарушения] с надписью «Просмотреть предыдущие действия» должна быть заполнена теми же действиями, что и другие категории для этого дела и участника.
У меня есть два участника в моем примере, как вы видите по [CaseParticipantID], у одного из которых [Action Taken] заполнено, а у другого нет.
Я предполагаю... данные могут быть объединены друг с другом с помощью номера дела и идентификатора участника дела, но я не знаю, как это сделать.
Данные из оператора SQL (представление ограничено только соответствующими столбцами для облегчения чтения)
Желаемый результат
Моя текущая инструкция SQL, отфильтрованная до одного случая:
SELECT
Cases.CaseNumber
,Cases.DateOpened
,Cases.DateClosed
,Participant.CaseParticipantId
,Participant.RoleInCase
,Participant.RelToOrganization
,Participant.Practice
,Participant.City
,Issues.Issue
,Issues.IssueSubCategory
,Issues.CaseIssueId
,Issues.Outcome
,ParticipantAlias.ParticipantName
,CaseAction.ActionTaken
FROM [Warehouse].[Table].[Case] as Cases
LEFT JOIN [Warehouse].[Table].[CaseParticipant] as Participant
ON Cases.CaseNumber = Participant.CaseNumber
LEFT JOIN [Warehouse].[Table].[CaseIssue] as Issues
ON Participant.CaseParticipantId = Issues.CaseParticipantId
LEFT JOIN [Warehouse].[Table].[CaseAction] as CaseAction
ON Issues.CaseIssueId = CaseAction.CaseIssueId
LEFT JOIN [Warehouse].[Table].[ParticipantAlias] as ParticipantAlias
ON Participant.ParticipantAliasId = ParticipantAlias.ParticipantAliasId
WHERE [Cases].[CaseNumber] = '123'
Буна Нет. В данном случае есть 2 таблицы: вставленная и удаленная.
Основываясь на вашем запросе, я не могу сказать, должно ли это быть представление или процедура, но я бы предложил сделать последнее. Вот пример того, как добиться ожидаемого вывода с помощью хранимой процедуры. Выход: Пример вывода хранимой процедуры
USE [Warehouse]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SP_GetCaseResult]
-- Add the parameters for the stored procedure here
@caseNumber as int
AS
BEGIN
SET NOCOUNT ON;
DROP TABLE IF EXISTS #Temp_table
-- 1. Original query into temp table
SELECT
Cases.CaseNumber
,Cases.DateOpened
,Cases.DateClosed
,Participant.CaseParticipantId
,Participant.CaseParticipantKey
,Participant.ParticipantAliasId
,Participant.RoleInCase
,Participant.RelToOrganization
,Participant.Practice
,Participant.City
,Issues.Issue
,Issues.IssueSubCategory
,Issues.CaseIssueId
,Issues.Outcome
,ParticipantAlias.ParticipantName
,CaseAction.ActionTaken
INTO #Temp_table
FROM [Warehouse].[Table].[Case] as Cases
LEFT JOIN
[Warehouse].[Table].[CaseParticipant] as Participant
ON Cases.CaseNumber = Participant.CaseNumber
LEFT JOIN
[Warehouse].[Table].[CaseIssue] as Issues
ON Participant.CaseParticipantId = Issues.CaseParticipantId
LEFT JOIN
[Warehouse].[Table].[CaseAction] as CaseAction
ON Issues.CaseIssueId = CaseAction.CaseIssueId
LEFT JOIN
[Warehouse].[Table].[ParticipantAlias] as ParticipantAlias
ON Participant.ParticipantAliasId = ParticipantAlias.ParticipantAliasId
WHERE [Cases].[CaseNumber] = @caseNumber
-- 2. Query from temptable without "See previous actions"
SELECT * FROM #Temp_table t1 WHERE t1.ActionTaken <> 'See Previous Actions'
-- "Joining" the two results
UNION ALL
-- 3. Query from temptable with joining the two table with and without "See previous actions" and getting needed output.
SELECT
t1.CaseNumber
,t1.DateOpened
,t1.DateClosed
,t1.CaseParticipantId
,t1.CaseParticipantKey
,t1.ParticipantAliasId
,t1.RoleInCase
,t1.RelToOrganization
,t1.Practice
,t1.City
,t1.Issue
,t1.IssueSubCategory
,t1.CaseIssueId
,t1.Outcome
,t1.ParticipantName
,t2.ActionTaken
FROM #Temp_table t2
INNER JOIN #Temp_table t1 ON t2.CaseNumber = t1.CaseNumber AND t2.CaseParticipantId = t1.CaseParticipantId
WHERE t1.ActionTaken = 'See Previous Actions' AND t2.ActionTaken <> 'See Previous Actions'
END
GO
ИЛИ Если вы действительно хотите это без хранимой процедуры: Вот пример:
DECLARE @caseNumber int = '123'
SELECT DISTINCT
t1.CaseNumber
,t1.DateOpened
,t1.DateClosed
,t1.CaseParticipantId
,t1.CaseParticipantKey
,t1.ParticipantAliasId
,t1.RoleInCase
,t1.RelToOrganization
,t1.Practice
,t1.City
,t1.Issue
,t1.IssueSubCategory
,t1.CaseIssueId
,t1.Outcome
,t1.ParticipantName
,t2.ActionTaken
FROM (
SELECT
Cases.CaseNumber
,Cases.DateOpened
,Cases.DateClosed
,Participant.CaseParticipantId
,Participant.CaseParticipantKey
,Participant.ParticipantAliasId
,Participant.RoleInCase
,Participant.RelToOrganization
,Participant.Practice
,Participant.City
,Issues.Issue
,Issues.IssueSubCategory
,Issues.CaseIssueId
,Issues.Outcome
,ParticipantAlias.ParticipantName
,CaseAction.ActionTaken
FROM [Warehouse].[Table].[Case] as Cases
LEFT JOIN
[Warehouse].[Table].[CaseParticipant] as Participant
ON Cases.CaseNumber = Participant.CaseNumber
LEFT JOIN
[Warehouse].[Table].[CaseIssue] as Issues
ON Participant.CaseParticipantId = Issues.CaseParticipantId
LEFT JOIN
[Warehouse].[Table].[CaseAction] as CaseAction
ON Issues.CaseIssueId = CaseAction.CaseIssueId
LEFT JOIN
[Warehouse].[Table].[ParticipantAlias] as ParticipantAlias
ON Participant.ParticipantAliasId = ParticipantAlias.ParticipantAliasId
WHERE [Cases].[CaseNumber] = @caseNumber --123
) t1
FULL OUTER JOIN (
SELECT
Cases.CaseNumber
,Cases.DateOpened
,Cases.DateClosed
,Participant.CaseParticipantId
,Participant.CaseParticipantKey
,Participant.ParticipantAliasId
,Participant.RoleInCase
,Participant.RelToOrganization
,Participant.Practice
,Participant.City
,Issues.Issue
,Issues.IssueSubCategory
,Issues.CaseIssueId
,Issues.Outcome
,ParticipantAlias.ParticipantName
,CaseAction.ActionTaken
FROM [Warehouse].[Table].[Case] as Cases
LEFT JOIN
[Warehouse].[Table].[CaseParticipant] as Participant
ON Cases.CaseNumber = Participant.CaseNumber
LEFT JOIN
[Warehouse].[Table].[CaseIssue] as Issues
ON Participant.CaseParticipantId = Issues.CaseParticipantId
LEFT JOIN
[Warehouse].[Table].[CaseAction] as CaseAction
ON Issues.CaseIssueId = CaseAction.CaseIssueId
LEFT JOIN
[Warehouse].[Table].[ParticipantAlias] as ParticipantAlias
ON Participant.ParticipantAliasId = ParticipantAlias.ParticipantAliasId
WHERE [Cases].[CaseNumber] = @caseNumber --123
) t2
ON t2.CaseNumber = t1.CaseNumber AND t2.CaseParticipantId = t1.CaseParticipantId
WHERE t2.ActionTaken <> 'See Previous Actions'
Из любопытства, почему не союз? Это то, что я пытаюсь сделать прямо сейчас
Вы можете добиться того же с объединением, как и в первом примере (хранимая процедура). Просто замените temptable запросом, использованным для его создания.
Вот образец UNION:
Однако, учитывая производительность, если ваши таблицы содержат сотни тысяч записей, то хранимая процедура является «самой быстрой», поскольку она запрашивает основные данные только один раз! (после этого используются временные таблицы).
В двух других примерах чем больше вы запрашиваете таблицы (которые содержат много данных), тем ниже будет производительность. Не будет большой разницы, если таблицы не содержат много данных внутри. Так что вам решать, какой метод вы выберете для получения ожидаемого результата.
DECLARE @caseNumber int = '123'
SELECT
Cases.CaseNumber
,Cases.DateOpened
,Cases.DateClosed
,Participant.CaseParticipantId
,Participant.CaseParticipantKey
,Participant.ParticipantAliasId
,Participant.RoleInCase
,Participant.RelToOrganization
,Participant.Practice
,Participant.City
,Issues.Issue
,Issues.IssueSubCategory
,Issues.CaseIssueId
,Issues.Outcome
,ParticipantAlias.ParticipantName
,CaseAction.ActionTaken
FROM [Warehouse].[Table].[Case] as Cases
LEFT JOIN
[Warehouse].[Table].[CaseParticipant] as Participant
ON Cases.CaseNumber = Participant.CaseNumber
LEFT JOIN
[Warehouse].[Table].[CaseIssue] as Issues
ON Participant.CaseParticipantId = Issues.CaseParticipantId
LEFT JOIN
[Warehouse].[Table].[CaseAction] as CaseAction
ON Issues.CaseIssueId = CaseAction.CaseIssueId
LEFT JOIN
[Warehouse].[Table].[ParticipantAlias] as ParticipantAlias
ON Participant.ParticipantAliasId = ParticipantAlias.ParticipantAliasId
WHERE [Cases].[CaseNumber] = @caseNumber AND [CaseAction].ActionTaken <> 'See Previous Actions'
UNION ALL
SELECT DISTINCT
t1.CaseNumber
,t1.DateOpened
,t1.DateClosed
,t1.CaseParticipantId
,t1.CaseParticipantKey
,t1.ParticipantAliasId
,t1.RoleInCase
,t1.RelToOrganization
,t1.Practice
,t1.City
,t1.Issue
,t1.IssueSubCategory
,t1.CaseIssueId
,t1.Outcome
,t1.ParticipantName
,t2.ActionTaken
FROM (
SELECT
Cases.CaseNumber
,Cases.DateOpened
,Cases.DateClosed
,Participant.CaseParticipantId
,Participant.CaseParticipantKey
,Participant.ParticipantAliasId
,Participant.RoleInCase
,Participant.RelToOrganization
,Participant.Practice
,Participant.City
,Issues.Issue
,Issues.IssueSubCategory
,Issues.CaseIssueId
,Issues.Outcome
,ParticipantAlias.ParticipantName
,CaseAction.ActionTaken
FROM [Warehouse].[Table].[Case] as Cases
LEFT JOIN
[Warehouse].[Table].[CaseParticipant] as Participant
ON Cases.CaseNumber = Participant.CaseNumber
LEFT JOIN
[Warehouse].[Table].[CaseIssue] as Issues
ON Participant.CaseParticipantId = Issues.CaseParticipantId
LEFT JOIN
[Warehouse].[Table].[CaseAction] as CaseAction
ON Issues.CaseIssueId = CaseAction.CaseIssueId
LEFT JOIN
[Warehouse].[Table].[ParticipantAlias] as ParticipantAlias
ON Participant.ParticipantAliasId = ParticipantAlias.ParticipantAliasId
WHERE [Cases].[CaseNumber] = @caseNumber AND [CaseAction].ActionTaken = 'See Previous Actions'
) t1
INNER JOIN (
SELECT
Cases.CaseNumber
,Cases.DateOpened
,Cases.DateClosed
,Participant.CaseParticipantId
,Participant.CaseParticipantKey
,Participant.ParticipantAliasId
,Participant.RoleInCase
,Participant.RelToOrganization
,Participant.Practice
,Participant.City
,Issues.Issue
,Issues.IssueSubCategory
,Issues.CaseIssueId
,Issues.Outcome
,ParticipantAlias.ParticipantName
,CaseAction.ActionTaken
FROM [Warehouse].[Table].[Case] as Cases
LEFT JOIN
[Warehouse].[Table].[CaseParticipant] as Participant
ON Cases.CaseNumber = Participant.CaseNumber
LEFT JOIN
[Warehouse].[Table].[CaseIssue] as Issues
ON Participant.CaseParticipantId = Issues.CaseParticipantId
LEFT JOIN
[Warehouse].[Table].[CaseAction] as CaseAction
ON Issues.CaseIssueId = CaseAction.CaseIssueId
LEFT JOIN
[Warehouse].[Table].[ParticipantAlias] as ParticipantAlias
ON Participant.ParticipantAliasId = ParticipantAlias.ParticipantAliasId
WHERE [Cases].[CaseNumber] = @caseNumber AND [CaseAction].ActionTaken <> 'See Previous Actions'
) t2
ON t2.CaseNumber = t1.CaseNumber AND t2.CaseParticipantId = t1.CaseParticipantId
Спасибо за объяснение, я вижу, что вы объявляете case # как целое число, что, если столбец содержит текст? Форматирование не то же самое, одни случаи целые, другие текст и числа, например: L1-23-84
Затем объявите его как nvarchar(max): DECLARE @caseNumber nvarchar(max) = '123' - в этом случае вам не нужно беспокоиться, является ли что-то числом или текстом.
Использование триггеров или предложение OUTPUT