I have this column in my table and I want to get all skipped transactions (which is a varchar)
SA1
SA3
SA50
SA999
I'm trying to get
SA2
SA4 to SA49
SA51 to SA998
EDIT: I've checked the actual data, found out that it's non-trailing zeroes.
I've done this with PHP. Was wondering if is there a way within SQL to do it?
This might sound dumb, but what I'm trying is to plot it like this (this returns null values)
WITH cte (id) AS (
SELECT ROW_NUMBER() OVER (ORDER BY s1.[object_id])
FROM sys.all_columns AS s1
CROSS JOIN sys.all_columns AS s2
),
table1 AS (
SELECT sNumber as id1 FROM Sales WHERE sNumber LIKE '%SI_'
),
table2 AS (
SELECT sNumber as id1 FROM Sales WHERE sNumber LIKE '%SI__'
),
table3 AS (
SELECT sNumber as id1 FROM Sales WHERE sNumber LIKE '%SI___'
)
SELECT
'SA' + RIGHT('' + CAST(t1.id AS VARCHAR(2)), 1) AS id_missing
FROM cte t1
LEFT JOIN table1 t2
ON t1.id = CAST(RIGHT(t2.id1, 1) AS INT)
WHERE
t1.id < (SELECT MAX(CAST(RIGHT(id1, 1) AS INT)) FROM yourTable1) AND
t2.id1 IS NULL
UNION ALL
SELECT
'SA' + RIGHT('' + CAST(t1.id AS VARCHAR(2)), 2) AS id_missing
FROM cte t1
LEFT JOIN table2 t2
ON t1.id = CAST(RIGHT(t2.id2, 2) AS INT)
WHERE
t1.id < (SELECT MAX(CAST(RIGHT(id2, 2) AS INT)) FROM yourTable2) AND
t2.id2 IS NULL
UNION ALL
SELECT
'SA' + RIGHT('' + CAST(t1.id AS VARCHAR(3)), 3) AS id_missing
FROM cte t1
LEFT JOIN table3 t2
ON t1.id = CAST(RIGHT(t2.id3, 3) AS INT)
WHERE
t1.id < (SELECT MAX(CAST(RIGHT(id3, 3) AS INT)) FROM yourTable3) AND
t2.id3 IS NULL
You may use a calendar table approach with a left join here:
WITH cte (id) AS (
SELECT ROW_NUMBER() OVER (ORDER BY s1.[object_id])
FROM sys.all_columns AS s1
CROSS JOIN sys.all_columns AS s2
)
SELECT
'SA' + RIGHT('000' + CAST(t1.id AS VARCHAR(3)), 3) AS id_missing
FROM cte t1
LEFT JOIN yourTable t2
ON t1.id = CAST(RIGHT(t2.id, 3) AS INT)
WHERE
t1.id < (SELECT MAX(CAST(RIGHT(id, 3) AS INT)) FROM yourTable) AND
t2.id IS NULL;
Demo
The idea is to generate a sequence of numbers covering the possible up to 1000 values which might appear in your current table as SAxxx. Then, we left join this calendar table to your current table, on the condition that the numeric portion of the id does not match. All such non matching SAxxx values are then retained in the result set.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have two tables as follow:
Let's say tbl1(Which keeps the main applicant info) and tbl2(the main applicant with family members info, note that we must keep the main applicant here too)
I'm trying to check whether the main applicant added oneself to tbl2 or not (that means if main applicant info is in tbl2)
CID FullName
-----------------------
1001 AYNALEM A NIGUSSIE
while in tbl2 (Same CID as tbl1):
HID CID FullName
-------------------------------------
1 1001 AYNALEM A NIGUSSIE
2 1001 CARLSTON HEITH
3 1001 Q LEE
I declared a variable to hold FullName list from tbl2 and compare the full name from tbl1 (to check if it exists in tbl2, function [dbo].[ufn_GetFullName] is used to get fullName from tbl1 ).
DECLARE #HH_FullName VARCHAR(250);
SELECT
#HH_FullName = (SELECT
STUFF((SELECT DISTINCT ', '+ DR.FullName
FROM
(SELECT DR.HID, DR.FullName
FROM dbo.tbl1 DR WITH(NOLOCK)
WHERE DR.CID = PC.CID) DR
FOR XML PATH(''), TYPE).value('.', 'varchar(max)'), 1, 2, ''))
FROM [dbo].[tbl2] PC WITH (NOLOCK)
LEFT JOIN [dbo].[tbl1] HC WITH (NOLOCK) ON HC.CID = PC.CID
WHERE PC.CID = 100037
/* --SELECT #HH_FullName -- 'AYNALEM A NIGUSSIE', 'CARLSTON
HEITH', 'Q LEE'
SELECT
(STUFF((SELECT ',''' + Val+''''
FROM
(SELECT CONVERT(VARCHAR(250), value) AS Val
FROM string_split(#HH_FullName, ',')) DF
FOR XML PATH('')), 1, 1, '')) -- 'AYNALEM A NIGUSSIE',' CARLSTON HEITH',' Q LEE'
SELECT CONVERT(VARCHAR(250), value) AS Val
FROM string_split(#HH_FullName, ',')
*/
SELECT *
FROM [dbo].[tbl1] PC WITH(NOLOCK)
LEFT JOIN [dbo].[tbl2] HC WITH(NOLOCK) ON HC.ClaimantID = PC.ClaimantID
WHERE HC.CID IS NOT NULL
AND ([dbo].[ufn_GetFullName](Pc.FirstName, Pc.MiddleName, Pc.LastName)
NOT IN ( SELECT ( STUFF((
SELECT ',''' + Val+''''
FROM (SELECT convert(VARCHAR(250), value) AS Val FROM string_split(#HH_FullName, ','))DF
FOR XML PATH('')
), 1, 1, '')) ))
-- OR as follow
SELECT * FROM [dbo].[tbl1] PC WITH(NOLOCK)
LEFT JOIN [dbo].[tbl2] HC WITH(NOLOCK) ON
HC.CID = PC.CID
WHERE HC.CID IS NOT NULL AND
( [dbo].[ufn_GetFullName]
(Pc.FirstName,Pc.MiddleName,Pc.LastName) NOT IN (SELECT convert(VARCHAR(250), value)
as VAL FROM string_split(#HH_FullName, ',') ) )
-- Also tried this way, it won't work either
SELECT * FROM [dbo].[tbl1] PC WITH(NOLOCK)
LEFT JOIN [dbo].[tbl2] HC WITH(NOLOCK) ON
HC.CID = PC.CID
WHERE HC.CID IS NOT NULL AND
( [dbo].[ufn_GetFullName]
(Pc.FirstName,Pc.MiddleName,Pc.LastName) NOT IN ( #HH_FullName )
WHERE Cond NOT IN (#HH_FullName) not returning the right value.
Like #UnhandledExcepSean commented you are complicating this beyond your stated objective...
I want to check if the FullName in tbl1 also exists in tbl2.
This statement will do it...
SELECT t1.*
FROM tbl1 AS t1
INNER JOIN tbl2 AS t2
ON CONCAT_WS(' ', t1.FirstName, t1.MiddleNAme, t1.LastName) = t2.FullName
This would work too...
SELECT t1.*
FROM tbl1 as t1
WHERE EXISTS (
SELECT * FROM tbl2
WHERE FullName = CONCAT_WS(' ', t1.FirstName, t1.MiddleNAme, t1.LastName))
Another way...
SELECT t1.*
FROM tbl1 as t1
WHERE CONCAT_WS(' ', t1.FirstName, t1.MiddleNAme, t1.LastName)
IN (SELECT FullName FROM tbl2)
You will have to account for the case where there is no middle name. Is it NULL or just an empty string? Or perhaps even spaces?
For small volumes of data you are not going to be able to detect a difference in performance. However, for larger amounts of data I believe you will be better off with the EXISTS approach.
This question already has an answer here:
SQL Server recursive self join
(1 answer)
Closed 3 years ago.
I have a SQL Server table that holds groups and subgroups that I am using to define user permissions in application. What I am trying to accomplish is to select all users ids from all subgroups based on used id assigned to group.
I have tried with this query but it only shows one level of subgroup users.
SET #UserIds =
ISNULL(
STUFF((SELECT ',' + CAST(tbl.UserID AS VARCHAR(MAX))
FROM
(SELECT grpUser.UserId AS UserID
FROM dbo.GroupUser grpUser
INNER JOIN (SELECT subGrp.Id, subGrp.GroupName
FROM dbo.Groups grp
INNER JOIN dbo.GroupUser guser ON grp.Id = guser.GroupId
AND guser.UserId = #UserId
INNER JOIN dbo.Groups subGrp ON grp.Id = subGrp.ParentGroupId) tbl ON grpUser.GroupId = tbl.Id) AS tbl
FOR XML PATH('')), 1, 1, ''), '')
I am struggling to get users ids in all subgroups. Number of subgroups is not defined. Is there a way to do in sql or should I shift this part to application side? Thank you for any advice.
Finally I came up with this code. Thank you for hint.
declare #UserGroupId int;
Set #UserGroupId = (Select GroupId from GroupUser gu
left join dbo.Groups gr on gu.GroupId = gr.id
where UserId = #UserId and gr.IsDeleted = 0)
declare #UsersGroups Table (
Id int not null,
GroupName nvarchar(50) not null
)
;WITH grp AS
(
SELECT Id, GroupName
FROM Groups
WHERE ParentGroupId = 1
UNION ALL
SELECT g.Id, g.GroupName
FROM Groups g
INNER JOIN dbo.GroupUser guser ON g.Id = guser.GroupId
INNER JOIN grp ON g.ParentGroupId = grp.Id
)
Insert into #UsersGroups
SELECT Id, GroupName
FROM grp
SET #UserIds = ISNULL(STUFF(( SELECT ',' + CAST(tbl.UserID AS VARCHAR(max)) FROM (
SELECT grpUser.UserId AS UserID FROM dbo.GroupUser grpUser
INNER JOIN ( SELECT * FROM #UsersGroups
) tbl ON grpUser.GroupId = tbl.Id
) AS tbl FOR XML PATH('') ), 1, 1, ''), '')
Having 2 tables with the same structure, like this SQLFiddle, is it possible to build a SQL statement that compares the values of the columns of both tables (where id is the unique key), and return a list of the change columns in the format:
columnname, oldvalue, newvalue
Where oldvalue is the value in Table1 and newvalue is the value in Table2.
You can do something like this:
SELECT T1.Id
,'Name' AS ColumnName
,CAST(T1.name AS VARCHAR(MAX)) AS OldValue
,CAST(T2.name AS VARCHAR(MAX)) AS NewValue
FROM Table1 AS T1
FULL OUTER JOIN Table2 AS T2
ON T1.id = T2.id
UNION
SELECT T1.Id
,'Amount'
,CAST(T1.amount AS VARCHAR(MAX))
,CAST(T2.amount AS VARCHAR(MAX))
FROM Table1 AS T1
FULL OUTER JOIN Table2 AS T2
ON T1.id = T2.id
You need to use a MERGE statement , please note it is only available from SQL 2008 onwards
here is an example
MERGE Production.ProductInventory AS target
USING (SELECT ProductID, SUM(OrderQty) FROM Sales.SalesOrderDetail AS sod
JOIN Sales.SalesOrderHeader AS soh
ON sod.SalesOrderID = soh.SalesOrderID
AND soh.OrderDate = #OrderDate
GROUP BY ProductID) AS source (ProductID, OrderQty)
ON (target.ProductID = source.ProductID)
WHEN MATCHED AND target.Quantity - source.OrderQty <= 0
THEN DELETE
WHEN MATCHED
THEN UPDATE SET target.Quantity = target.Quantity - source.OrderQty,
target.ModifiedDate = GETDATE()
OUTPUT $action, Inserted.ProductID, Inserted.Quantity, Inserted.ModifiedDate, Deleted.ProductID,
Deleted.Quantity, Deleted.ModifiedDate;
GO
you can learn more about merge's here SQL merge
if you only want rows with differences:
SELECT COALESCE(T1.Id, T2.Id) Id
,'Name' AS ColumnName
,CAST(T1.name AS VARCHAR(MAX)) AS OldValue
,CAST(T2.name AS VARCHAR(MAX)) AS NewValue
FROM Table1 AS T1
FULL OUTER JOIN Table2 AS T2
ON T1.id = T2.id
WHERE COALESCE(T1.name,'**') != COALESCE(T2.name ,'**')
UNION ALL
SELECT COALESCE(T1.Id, T2.Id) Id
,'Amount' AS ColumnName
,CAST(T1.Amount AS VARCHAR(MAX)) AS OldValue
,CAST(T2.Amount AS VARCHAR(MAX)) AS NewValue
FROM Table1 AS T1
FULL OUTER JOIN Table2 AS T2
ON T1.id = T2.id
WHERE COALESCE(T1.Amount,0) != COALESCE(T2.Amount,0)
I have a stored procedure on my SQL Server that consolidates a range of fields for use in SSRS for Report Builder. The procedure is fed a FileId and then works its logic. It works as intended until the File can't find or reference the Solicitor and Arresting Officer fields.
I need this to return a result even if the fileId does not have an Arresting Officer or Solicitor associated. I'm sure its something simple. Basically if the CTE returns nothing from the query, I still need a default row.
ALTER PROCEDURE [dbo].[GetRollCallData]
#Ids VARCHAR(255),
#LexiconId INT,
#UUID UNIQUEIDENTIFIER,
#ReadOnly INT
AS
DECLARE #TableCode INT
SET #TableCode = 58
IF #Ids <> ''
BEGIN
EXEC InsertInSelectionCache #Ids, #UUID, #TableCode, 0
IF #ReadOnly = 1
WITH DOACTE AS(
SELECT ROW_NUMBER() OVER(PARTITION BY [File].Id ORDER BY CustomRecordsetId DESC) AS RowNumber, [File].*, FileType2Lexicon.Label as FileTypeLabel, [People].DefaultPhone, [People].InvertedName, CustomField.Name as FieldLabel, CustomFieldValue.Value as FieldValue
FROM FileType2Lexicon, SelectionCache, [People], [File]
INNER JOIN [CustomRecordSet]
ON [CustomRecordset].RecordId = [File].Id
INNER JOIN CustomFieldValue
ON [CustomRecordset].Id = CustomFieldValue.CustomRecordsetId
INNER JOIN [CustomField2Lexicon]
ON CustomField2Lexicon.CustomFieldId = CustomFieldValue.CustomFieldId
INNER JOIN [CustomField]
ON CustomField.Id = CustomField2Lexicon.CustomFieldId
WHERE [File].Id = SelectionCache.RecordId
AND SelectionCache.UUID = #UUID
AND SelectionCache.TableCode = #TableCode -- this is the code for File table
AND [File].Id <> 0
AND [File].FileTypeId = FileType2Lexicon.FileTypeId
AND FileType2Lexicon.LexiconId = #LexiconId
AND [File].ClientIdString = [People].ClientIdString
AND CustomFieldValue.Value <> ''),
SolicitorCTE AS(
SELECT [People].Name AS SolicitorName, [File].Id
FROM SelectionCache, [File]
INNER JOIN [People2File]
ON [People2File].FileId = [File].Id
INNER JOIN [Role2Lexicon]
ON [Role2Lexicon].RoleId = [People2File].RoleId
INNER JOIN [People]
ON [People].Id = [People2File].PeopleId
WHERE
[File].Id = SelectionCache.RecordId
AND SelectionCache.UUID = #UUID
AND SelectionCache.TableCode = #TableCode -- this is the code for File table
AND [File].Id <> 0
AND [Role2Lexicon].Label = 'Solicitor'),
ArrestingOfficerCTE AS(
SELECT ROW_NUMBER() OVER(PARTITION BY [File].Id ORDER BY [People].InvertedName ASC) AS RowNumber, [People].Name AS ArrestingOfficerName, [People].CompanyName AS ArrestingOfficerCompany, [File].Id
FROM SelectionCache, [File]
INNER JOIN [People2File]
ON [People2File].FileId = [File].Id
INNER JOIN [Role2Lexicon]
ON [Role2Lexicon].RoleId = [People2File].RoleId
INNER JOIN [People]
ON [People].Id = [People2File].PeopleId
WHERE
[File].Id = SelectionCache.RecordId
AND SelectionCache.UUID = #UUID
AND SelectionCache.TableCode = #TableCode -- this is the code for File table
AND [File].Id <> 0
AND [Role2Lexicon].Label = 'Arresting Officer'),
PivotCTE AS(
SELECT *
FROM
(Select Id, FieldLabel, FieldValue FROM DOACTE) AS Source
PIVOT(
MAX(FieldValue) FOR FieldLabel IN ([Date_Arrest], [Graphic_Client], [Ticket_1], [Ticket_2], [Ticket_3], [Ticket_4], [Ticket_5], [Charge_1], [Charge_2], [Charge_3], [Charge_4], [Charge_5])) as Pvt
)
SELECT DOACTE.*, COALESCE(ArrestingOfficerCTE.ArrestingOfficerCompany, 'NULL')AS ArrestingOfficerCompany, COALESCE(ArrestingOfficerCTE.ArrestingOfficerName, 'NULL') AS ArrestingOfficerName, SolicitorCTE.SolicitorName, PivotCTE.[Date_Arrest], dbo.GetImagebyId(PivotCTE.[Graphic_Client]) as Photo, PivotCTE.[Ticket_1], PivotCTE.[Ticket_2], PivotCTE.[Ticket_3], PivotCTE.[Ticket_4], PivotCTE.[Ticket_5], PivotCTE.[Charge_1], PivotCTE.[Charge_2], PivotCTE.[Charge_3], PivotCTE.[Charge_4], PivotCTE.[Charge_5]
FROM DOACTE
INNER JOIN
PivotCTE
ON DOACTE.Id = PivotCTE.Id
INNER JOIN
SolicitorCTE
ON DOACTE.Id = SolicitorCTE.Id
INNER JOIN
ArrestingOfficerCTE
ON DOACTE.Id = ArrestingOfficerCTE.Id
WHERE DOACTE.RowNumber = 1
AND ArrestingOfficerCTE.RowNumber = 1
ELSE
DELETE SelectionCache
WHERE UUID = #UUID
AND TableCode = #TableCode
END
You can left join for optional results. I also needed to add a null check for the Arresting officer to the where caluse so that this didn't exclude records despite the left join.
SELECT DOACTE.*, COALESCE(ArrestingOfficerCTE.ArrestingOfficerCompany, 'NULL')AS ArrestingOfficerCompany, COALESCE(ArrestingOfficerCTE.ArrestingOfficerName, 'NULL') AS ArrestingOfficerName, SolicitorCTE.SolicitorName, PivotCTE.[Date_Arrest], dbo.GetImagebyId(PivotCTE.[Graphic_Client]) as Photo, PivotCTE.[Ticket_1], PivotCTE.[Ticket_2], PivotCTE.[Ticket_3], PivotCTE.[Ticket_4], PivotCTE.[Ticket_5], PivotCTE.[Charge_1], PivotCTE.[Charge_2], PivotCTE.[Charge_3], PivotCTE.[Charge_4], PivotCTE.[Charge_5]
FROM DOACTE
INNER JOIN
PivotCTE
ON DOACTE.Id = PivotCTE.Id
LEFT JOIN
SolicitorCTE
ON DOACTE.Id = SolicitorCTE.Id
LEFT JOIN
ArrestingOfficerCTE
ON DOACTE.Id = ArrestingOfficerCTE.Id
WHERE DOACTE.RowNumber = 1
AND ( ArrestingOfficerCTE.RowNumber = 1 or ArrestingOfficerCTE.RowNumber is null )
Can you try:
SELECT DOACTE.*, COALESCE(ArrestingOfficerCTE.ArrestingOfficerCompany, 'NULL')AS ArrestingOfficerCompany, COALESCE(ArrestingOfficerCTE.ArrestingOfficerName, 'NULL') AS ArrestingOfficerName, SolicitorCTE.SolicitorName, PivotCTE.[Date_Arrest], dbo.GetImagebyId(PivotCTE.[Graphic_Client]) as Photo, PivotCTE.[Ticket_1], PivotCTE.[Ticket_2], PivotCTE.[Ticket_3], PivotCTE.[Ticket_4], PivotCTE.[Ticket_5], PivotCTE.[Charge_1], PivotCTE.[Charge_2], PivotCTE.[Charge_3], PivotCTE.[Charge_4], PivotCTE.[Charge_5]
into #Results
FROM DOACTE
INNER JOIN
PivotCTE
ON DOACTE.Id = PivotCTE.Id
INNER JOIN
SolicitorCTE
ON DOACTE.Id = SolicitorCTE.Id
INNER JOIN
ArrestingOfficerCTE
ON DOACTE.Id = ArrestingOfficerCTE.Id
WHERE DOACTE.RowNumber = 1
AND ArrestingOfficerCTE.RowNumber = 1
if ((select cout(*) from #Results) = 0)
begin
insert into #Results
select
.......your default values......
end
select * from #Results
drop table #Results
This is pretty much liebs19's answer, so I upvoted his since he got there first. I think the answer comes down to LEFT JOINing where you're INNER. Since I rewrote your query so I could actually understand what was going on and I made some changes you may or may not want, so I'll leave it here in case it's useful.
Mine is more lines than yours partially because I format differently, partially because I'm using a temp table to do once what you do around 4 times. Thing about CTE's is that when you stack them like this you're likely to get some really gnarly performance. The CTE's act basically like an on-the-fly view, and their SQL pretty much gets repeated everywhere. I'm taking your limiting [File] and moving it into a temp table. Then I'm pivoting it into another one (since this further limits things based on RowNumber being 1. Then I just use this with the 2 CTE's at the end and into your final result.
Lastly, SELECT * ... is evil. I only use it when I'm poking around querying for something. Putting it into a sproc like this will cause you issues as the schema or CTE's or so on change. When you're making a sproc, name every column, it'll bite you much less in the future.
Here it is, feel free to ignore if you don't find it useful:
ALTER PROCEDURE [dbo].[GetRollCallData]
#Ids VARCHAR(255),
#LexiconId INT,
#UUID UNIQUEIDENTIFIER,
#ReadOnly INT
AS
BEGIN
DECLARE #TableCode INT = 58;
IF #Ids <> ''
BEGIN
EXEC InsertInSelectionCache #Ids, #UUID, #TableCode, 0
IF #ReadOnly = 1
BEGIN
SELECT
-- Add any other fully qualified columns. * is evil for sprocs. Only good for poking around in your own queries.
AllFiles.Id
INTO #SelectionFile
FROM
[File] AllFiles
INNER JOIN SelectionCache Cache
ON Cache.RecordId = AllFiles.Id
AND Cache.UUID = #UUID
AND Cache.TableCode = #TableCode -- this is the code for File table
WHERE
AllFiles.Id <> 0
;WITH DOACTE AS
(
SELECT
ROW_NUMBER() OVER(PARTITION BY SelectionFile.Id ORDER BY CustomRecordsetId DESC) AS RowNumber
, SelectionFile.Id AS FileId
-- [Replace with any other columns that you selected from [File] at the top.]
, Lexicon.Label AS FileTypeLabel
, [People].DefaultPhone
, [People].InvertedName
, CustomField.Name AS FieldLabel
, CustomFieldValue.Value AS FieldValue
FROM
#SelectionFile SelectionFile
INNER JOIN FileType2Lexicon Lexicon
ON Lexicon.FileTypeId = SelectionFile.FileTypeId
AND Lexicon.LexiconId = #LexiconId
INNER JOIN [People]
ON [People].ClientIdString = SelectionFile.ClientIdString
INNER JOIN [CustomRecordSet]
ON [CustomRecordset].RecordId = SelectionFile.Id
INNER JOIN CustomFieldValue
ON [CustomRecordset].Id = CustomFieldValue.CustomRecordsetId
AND CustomFieldValue.Value <> ''
INNER JOIN [CustomField2Lexicon]
ON CustomField2Lexicon.CustomFieldId = CustomFieldValue.CustomFieldId
INNER JOIN [CustomField]
ON CustomField.Id = CustomField2Lexicon.CustomFieldId
)
SELECT
Pvt.FileId
-- [Replace with any other columns that you selected from DOACTE you want to propagate to the end.]
, Pvt.[Date_Arrest]
, Pvt.[Graphic_Client]
, Pvt.[Ticket_1]
, Pvt.[Ticket_2]
, Pvt.[Ticket_3]
, Pvt.[Ticket_4]
, Pvt.[Ticket_5]
, Pvt.[Charge_1]
, Pvt.[Charge_2]
, Pvt.[Charge_3]
, Pvt.[Charge_4]
, Pvt.[Charge_5]
INTO #PivotedFile
FROM
(
SELECT
FileId
-- [Replace with any other columns that you selected from DOACTE you want to propagate to the end.]
, FieldLabel
, FieldValue
, FieldLabel AS PivotFieldLabel
, FieldValue AS PivotFieldValue
FROM
DOACTE
WHERE
RowNumber = 1
) AS Source
PIVOT
(
MAX(PivotFieldValue)
FOR PivotFieldLabel
IN
(
[Date_Arrest]
, [Graphic_Client]
, [Ticket_1]
, [Ticket_2]
, [Ticket_3]
, [Ticket_4]
, [Ticket_5]
, [Charge_1]
, [Charge_2]
, [Charge_3]
, [Charge_4]
, [Charge_5]
)
) as Pvt
;WITH SolicitorCTE AS
(
SELECT
[People].Name AS SolicitorName
, SelectedFiles.FileId
FROM
#PivotedFile SelectedFiles
INNER JOIN [People2File]
ON [People2File].FileId = SelectedFiles.FileId
INNER JOIN [Role2Lexicon]
ON [Role2Lexicon].RoleId = [People2File].RoleId
AND [Role2Lexicon].Label = 'Solicitor'
INNER JOIN [People]
ON [People].Id = [People2File].PeopleId
)
, ArrestingOfficerCTE AS
(
SELECT
ROW_NUMBER() OVER(PARTITION BY SelectionFile.Id ORDER BY [People].InvertedName ASC) AS RowNumber
, [People].Name AS ArrestingOfficerName
, [People].CompanyName AS ArrestingOfficerCompany
, SelectedFiles.FileId
FROM
#PivotedFile SelectedFiles
INNER JOIN [People2File]
ON [People2File].FileId = SelectedFiles.FileId
INNER JOIN [Role2Lexicon]
ON [Role2Lexicon].RoleId = [People2File].RoleId
AND [Role2Lexicon].Label = 'Arresting Officer'
INNER JOIN [People]
ON [People].Id = [People2File].PeopleId
)
SELECT
SelectedFiles.Id
-- [Replace with any other columns that you selected from DOACTE you want to propagate to the end.]
, COALESCE(ArrestingOfficerCTE.ArrestingOfficerCompany, 'NULL') AS ArrestingOfficerCompany
, COALESCE(ArrestingOfficerCTE.ArrestingOfficerName, 'NULL') AS ArrestingOfficerName
, SolicitorCTE.SolicitorName
, SelectedFiles.[Date_Arrest]
, dbo.GetImagebyId(SelectedFiles.[Graphic_Client]) as Photo
, SelectedFiles.[Ticket_1]
, SelectedFiles.[Ticket_2]
, SelectedFiles.[Ticket_3]
, SelectedFiles.[Ticket_4]
, SelectedFiles.[Ticket_5]
, SelectedFiles.[Charge_1]
, SelectedFiles.[Charge_2]
, SelectedFiles.[Charge_3]
, SelectedFiles.[Charge_4]
, SelectedFiles.[Charge_5]
FROM #PivotedFile SelectedFiles
LEFT JOIN SolicitorCTE
ON SelectedFiles.FileId = SolicitorCTE.FileId
LEFT JOIN ArrestingOfficerCTE
ON SelectedFiles.FileId = ArrestingOfficerCTE.FileId
AND ArrestingOfficerCTE.RowNumber = 1
DROP TABLE #SelectionFile
DROP TABLE #PivotedFile
END
ELSE
DELETE SelectionCache
WHERE
UUID = #UUID
AND TableCode = #TableCode
END
END
(If you do use it, read the -- [Replace...] comments.