Related
My Application is a cash register. The following query takes a TransactionID and returns one or more rows of items sold in this single transaction i.e. for TransactionID = 28715:
DECLARE #SalesItems varchar(250);
DECLARE #TransactionID int;
SET #TransactionID = 28715;
Select #SalesItems = coalesce(#SalesItems + ', ', '') + CAST(TransactionsPosLines.Description as varchar(250))
From
TransactionsPosLines
where TransactionsPosLines.TransactionId = #TransactionID
select #SalesItems
and returns:
"Widget A, Widget B, Widget C" as a single string.
I also have an end of day transaction report which I want to append the string (Widget A etc...) onto the end of the transaction report.
Select
Transactions.TransactionId,
Transactions.TransactionDate,
Transactions.MoneyIn,
Transactions.MoneyOut,
Transactions.Description,
PaymentMethods.PaymentMethodName,
Transactions.TransactionRef,
Membership.Username,
Tills.Description As 'Till Name',
Transactions.Reason,
-- FOR THIS LAST COLUMN HERE I WANT TO SHOW THE OUTPUT OF THE QUERY ABOVE
====> SalesItems
From
Transactions Left Outer Join
Tills
On Transactions.TillId = Tills.TillId Inner Join
PaymentMethods
On Transactions.PaymentMethodId = PaymentMethods.PaymentMethodsID Inner Join
Membership
On Transactions.UserId = Membership.UserId Inner Join
Where
Transactions.TransactionDate >= #DateStart And
Transactions.TransactionDate <= #DateEnd
So when I run this report I get something like this:
TransactionId TransactionDate MoneyIn MoneyOut Description PaymentMethodName TransactionRef Username Till Name Reason SalesItems
28715 31/08/2016 09:07 119.99 0 Sale - Card Card 24881 Chantal Till1 Null Widget A, Widget B, Widget C
CROSS APPLY WITH FOR XML CONCATENATION METHOD:
Select
t.TransactionId,
t.TransactionDate,
t.MoneyIn,
t.MoneyOut,
t.Description,
p.PaymentMethodName,
t.TransactionRef,
m.Username,
tl.Description As 'Till Name',
t.Reason,
c.SalesItems
From
Transactions t
LEFT JOIN Tills tl
ON t.TillId = tl.TillId
INNER JOIN PaymentMethods p
ON t.PaymentMethodId = p.PaymentMethodID
INNER JOIN Membership m
On t.UserId = m.UserId
CROSS APPLY
(SELECT STUFF(
(SELECT ',' + CAST(tp.Description AS VARCHAR(100))
FROM
TransactionPostLines tp
WHERE t.TransactionId = tp.TransactionId
FOR XML PATH(''))
,1,1,'') as SalesItems) c
Where
t.TransactionDate >= #DateStart
AND t.TransactionDate <= #DateEnd
AS Sub Select in column Definition:
Select
t.TransactionId,
t.TransactionDate,
t.MoneyIn,
t.MoneyOut,
t.Description,
p.PaymentMethodName,
t.TransactionRef,
m.Username,
tl.Description As 'Till Name',
t.Reason,
STUFF(
(SELECT ',' + CAST(tp.Description AS VARCHAR(100))
FROM
TransactionPostLines tp
WHERE t.TransactionId = tp.TransactionId
FOR XML PATH(''))
,1,1,'') as SalesItems
From
Transactions t
LEFT JOIN Tills tl
ON t.TillId = tl.TillId
INNER JOIN PaymentMethods p
ON t.PaymentMethodId = p.PaymentMethodID
INNER JOIN Membership m
On t.UserId = m.UserId
Where
t.TransactionDate >= #DateStart
AND t.TransactionDate <= #DateEnd
Note using table aliases makes the code easier to read and to write!
I have used cross apply in order to apply result to inner query to each row of your main query. Check whether this helps you:
Select
Transactions.TransactionId,
Transactions.TransactionDate,
Transactions.MoneyIn,
Transactions.MoneyOut,
Transactions.Description,
PaymentMethods.PaymentMethodName,
Transactions.TransactionRef,
Membership.Username,
Tills.Description As 'Till Name',
Transactions.Reason,
-- HERE >>
--SalesItems =
dt.salesItems
From
Transactions Left Outer Join
Tills
On Transactions.TillId = Tills.TillId Inner Join
PaymentMethods
On Transactions.PaymentMethodId = PaymentMethods.PaymentMethodsID Inner Join
Membership
On Transactions.UserId = Membership.UserId
cross apply (
select distinct stuff((
Select ',' + CAST(TransactionsPosLines.Description as varchar(250))
From
TransactionsPosLines
where TransactionsPosLines.TransactionId = Transactions.TransactionId
FOR XML PATH('')),1,1,'') as salesItems
) as dt
-- TransactionsPosLines
-- On TransactionsPosLines.TransactionId = Transactions.TransactionId
Where
Transactions.TransactionDate >= #DateStart And
Transactions.TransactionDate <= #DateEnd
I have this SQL Server code. Everything works except it duplicates rows with same RightsId and UserId. The where not exists clause is not working.
Any help is appreciated.
INSERT INTO dbo.UserAccessRights (Id, UserId, RightType, RightsId, CreatedOn, CreatedBy)
SELECT DISTINCT
NEWID(),
#changedUserId,
N'Process ' + #rightsTypeSuffix,
ptm.ProcessInstance_id,
getdate(),
#loggedInUserId
FROM
dbo.ProcessTeamMembers ptm WITH (NOLOCK)
INNER JOIN
dbo.Users u WITH (NOLOCK) ON ptm.TeamMemberProfile_id = u.ProfileID
AND u.Id = #changedUserId
AND ptm.TenantId = #tenantId
INNER JOIN
dbo.ProcessInstances p_i WITH (NOLOCK) ON p_i.Id = ptm.ProcessInstance_id
AND p_i.DeletedOn IS NULL
WHERE
NOT EXISTS (SELECT *
FROM UserAccessRights uar WITH (NOLOCK)
WHERE uar.UserId = #changedUserId
AND uar.RightsId = ptm.ProcessInstance_id)
Your duplicates are probably coming from within the query, rather than from existing rows in the table. Possibly, the problem is that the select distinct isn't doing anything -- because newid() is always unique.
My recommendation is to change the id column to have a default value of newid(). Then you don't need to insert it and the select distinct will work. Absent that, you can fix the query:
INSERT INTO dbo.UserAccessRights (Id, UserId, RightType, RightsId, CreatedOn, CreatedBy)
SELECT DISTINCT NEWID(), #changedUserId, N'Process ' + #rightsTypeSuffix,
ProcessInstance_id, getdate(), #loggedInUserId
FROM (SELECT DISTINCT ptm.ProcessInstance_id
FROM dbo.ProcessTeamMembers ptm WITH (NOLOCK) INNER JOIN
dbo.Users u WITH (NOLOCK)
ON ptm.TeamMemberProfile_id = u.ProfileID AND
u.Id = #changedUserId AND
ptm.TenantId = #tenantId INNER JOIN
dbo.ProcessInstances p_i WITH (NOLOCK)
ON p_i.Id = ptm.ProcessInstance_id AND
p_i.DeletedOn IS NULL
WHERE NOT EXISTS (SELECT 1
FROM UserAccessRights uar WITH (NOLOCK)
WHERE uar.UserId = #changedUserId AND
uar.RightsId = ptm.ProcessInstance_id
)
) t;
Hmmm, as I think about this, perhaps you should be using TOP 1 rather than SELECT DISTINCT. I'm not sure which columns cause the problem on the distinct, but you are inserting the same value in many columns, so more than one row might cause an issue.
Try the "Left Excluding Join" (See Visual Representation of SQL Joins) instead of the WHERE NOT EXISTS clause.
INSERT INTO dbo.UserAccessRights (Id, UserId, RightType, RightsId, CreatedOn, CreatedBy)
SELECT DISTINCT
NEWID(),
#changedUserId,
N'Process ' + #rightsTypeSuffix,
ptm.ProcessInstance_id,
getdate(),
#loggedInUserId
FROM
dbo.ProcessTeamMembers ptm
INNER JOIN
dbo.Users u ON ptm.TeamMemberProfile_id = u.ProfileID
AND u.Id = #changedUserId
AND ptm.TenantId = #tenantId
INNER JOIN
dbo.ProcessInstances p_i ON p_i.Id = ptm.ProcessInstance_id
AND p_i.DeletedOn IS NULL
LEFT JOIN UserAccessRights uar
ON uar.UserId = u.Id
AND uar.RightsId = ptm.ProcessInstance_id
WHERE
uar.Id IS NULL -- Replace with the actual pkey on UserAccessRights if not Id
I need help with a pivot table if possible. Not sure it can be done. Below is my example.
Questions
Answers
User Answers
Answer Pivot
Thanks For any help.
I have attached a screenshot of db results with the pivot working . The code below pivot as it should and that works fine. If you can look at the column "Subject has exp..." I would like the column repeated three times, The heading is the question, But I also would like each possible answer to shown with the question as well.
Thank Again!
Thansk Again.
Here Is a Sample of the Code:
DECLARE #columns VARCHAR(MAX)
SELECT #columns = COALESCE(#columns + ','+QUOTENAME([QuestionText]),QUOTENAME([QuestionText]))
FROM SchemaWema.vts_vwSurvey INNER JOIN
Question ON SchemaWema.vts_vwSurvey.SurveyID = SchemaWema.vts_vwQuestion.SurveyID
WHERE SchemaWema.vts_vwSurvey.DecisionSetId = 598 AND SchemaWema.vts_vwSurvey.FormType = 1
Set #columns = REPLACE(#columns, '[]', '[No Name Given]')
DECLARE #sql NVARCHAR(MAX)=N' SELECT * FROM
(
SELECT Project.PROJECTNAME, Project.ID,
Sites.PROJECTSTUDYSITENUMBER, Sites.PROJECTSTUDYSITENAME,
Study.PROJECTSTUDYNAME, Study.PROJECTSTUDYNUMBER,
Survey.SurveyID, Question.QuestionID, Cases.SITEID, Cases.EVENTDATE,
Cases.SUBJNO, Cases.EventType, Cases.TriggerEvent,
Cases.DecisionSetID, Cases.PanelID, Cases.RECORDSTATUS,
Project.PROJECTSPONSOR, VoterAnswers.AnswerID, VoterAnswers.VoterID,
VoterAnswers.AnswerText AS FreeTypedAnswers, Voter.VoteDate, Users.SHOWNNAME, Panel.PANELNAME, Sites.COUNTRY,
Cases.VERSIONID, cases.CSID, cases.CASENUMBER,Cases.CASEDATEUPDATED AS LASTUPDATED,
Cases.DECISIONSETNAME,
Question.QuestionText,
CASE
WHEN
CAST(VoterAnswers.AnswerText AS VARCHAR(MAX)) IS NULL OR CAST(VoterAnswers.AnswerText AS VARCHAR(MAX)) = ''''
THEN
Answer.AnswerText
ELSE
CAST(Answer.AnswerText AS VARCHAR(MAX))
END AS AnswerText
FROM
(
SELECT a.ID, a.STUDYID, a.SITEID, a.CSID, a.VERSIONID, a.CASENUMBER, a.CASEINITIALS, a.EVENTDATE, a.CASEDETAILSFILE, a.CASEDETAILSFILEVERSION,
a.CASESTATUS, a.RECORDSTATUS, a.CASEDATEUPDATED, a.PROJECTDATEUPDATED, a.PanelID, a.DecisionSetID, a.SUBJNO, a.EventType, a.TriggerEvent,
a.Priority, a.id1, a.id2, a.dateid, a.dateiddt1, a.dateiddt2, a.extratext1, a.extratext2, SchemaWema.PROJECTPANELDECISIONSETVIEW.DECISIONSETNAME
FROM SchemaWema.PROJECTCASE AS a LEFT OUTER JOIN
SchemaWema.PROJECTPANELDECISIONSETVIEW ON a.DecisionSetID = SchemaWema.PROJECTPANELDECISIONSETVIEW.DECISIONSETID
WHERE (a.CASEDATEUPDATED =
(SELECT MAX(CASEDATEUPDATED) AS Expr1
FROM SchemaWema.PROJECTCASE AS b
WHERE (a.ID = PROJECTID) AND (a.CSID = CASEID) AND (a.VERSIONID = VERSIONID) )) AND (a.RECORDSTATUS <> ''D'')
)Cases
LEFT OUTER JOIN
(
SELECT PROJECTID, PROJECTNAME, PROJECTSPONSOR
FROM SchemaWema.PROJECT AS a
WHERE (PROJECTDATEUPDATED =
(SELECT MAX(PROJECTDATEUPDATED) AS Expr1
FROM SchemaWema.PROJECT AS b
WHERE (a.ID = PROJECTID))) AND (RECORDSTATUS <> ''D'')
) Project on
Project.ID = Cases.ID
LEFT OUTER JOIN
(
SELECT DISTINCT a.ID, a.STUDYID, a.SITEID, a.PROJECTSTUDYSITENAME, a.PROJECTSTUDYSITENUMBER, SchemaWema.PROJECTSTUDYVIEW.PROJECTSTUDYNAME, a.COUNTRY
FROM SchemaWema.PROJECTSTUDYSITE AS a INNER JOIN
SchemaWema.PROJECTVIEW ON a.ID = SchemaWema.PROJECTVIEW.ID INNER JOIN
SchemaWema.PROJECTSTUDYVIEW ON a.ID = SchemaWema.PROJECTSTUDYVIEW.ID AND
a.STUDYID = SchemaWema.PROJECTSTUDYVIEW.STUDYID
WHERE (a.PROJECTSTUDYSITEDATEUPDATED =
(SELECT MAX(PROJECTSTUDYSITEDATEUPDATED) AS Expr1
FROM SchemaWema.PROJECTSTUDYSITE AS b
WHERE (a.ID = PROJECTID) AND (a.STUDYID = STUDYID) AND (a.SITEID = SITEID))) AND (a.RECORDSTATUS <> ''D'')
)Sites on
Cases.SITEID = Sites.SITEID
LEFT OUTER JOIN
(
SELECT DISTINCT PROJECTID, STUDYID, PROJECTSTUDYNAME, PROJECTSTUDYNUMBER, PROJECTSTUDYDESCRIPTION
FROM SchemaWema.PROJECTSTUDY AS a
WHERE (PROJECTSTUDYDATEUPDATED =
(SELECT MAX(PROJECTSTUDYDATEUPDATED) AS Expr1
FROM SchemaWema.PROJECTSTUDY AS b
WHERE (a.ID = PROJECTID) AND (ISNULL(a.STUDYID, ''0'') = ISNULL(STUDYID, ''0'')))) AND (RECORDSTATUS <> ''D'')
)Study on
Study.STUDYID = Cases.STUDYID
inner join
(
SELECT VoterID, UID, SurveyID, ContextUserName, VoteDate, StartDate, IPSource, Validated, ResumeUID, ResumeAtPageNumber, ProgressSaveDate,
ResumeQuestionNumber, ResumeHighestPageNumber, LanguageCode, SurveyStatus, VoteAcceptRejectDate, CaseID, VersionID, PdfFileName, voterSurveyStatus,
dateupdated, recordstatus, modifiedby, changereason
FROM SchemaWema.vts_tbVoter AS a
WHERE (dateupdated =
(SELECT MAX(dateupdated) AS Expr1
FROM SchemaWema.vts_tbVoter AS b
WHERE (a.VoterID = VoterID) AND (a.SurveyID = SurveyID) AND (a.CSID = CaseID) AND (a.VersionID = VersionID)))
) Voter on
Voter.CSID = Cases.CSID
AND Voter.VersionID = Cases.VersionID
Inner Join
(
SELECT DISTINCT SurveyID, DecisionSetId, FormType
FROM SchemaWema.vts_tbSurvey AS a
WHERE (dateupdated =
(SELECT MAX(dateupdated) AS Expr1
FROM SchemaWema.vts_tbSurvey AS b
WHERE (a.SurveyID = SurveyID))) AND (recordstatus <> ''D'')
) Survey on
Survey.SurveyID = Voter.SurveyID
inner Join
(
SELECT DISTINCT
VoterID, AnswerID, SectionNumber, CAST(AnswerText AS varchar(MAX)) AnswerText, SurveyID, CaseID, versionID
FROM SchemaWema.vts_tbVoterAnswers AS a
WHERE (dateupdated =
(SELECT MAX(dateupdated) AS Expr1
FROM SchemaWema.vts_tbVoterAnswers AS b
WHERE (a.VoterID = VoterID) AND (a.AnswerID = AnswerID) AND (a.SectionNumber = SectionNumber) AND (a.SurveyID = SurveyID) AND (a.CSID = CaseID) AND
(a.versionID = versionID))) AND (recordstatus <> ''D'')
)VoterAnswers on
VoterAnswers.SurveyID = Survey.SurveyID
AND VoterAnswers.CSID = Voter.CSID
AND Voter.VoterID = VoterAnswers.VoterID
AND VoterAnswers.versionID = Voter.versionID
AND VoterAnswers.SurveyID = Voter.SurveyID
FULL OUTER JOIN
(
select DISTINCT a.USERID, a.USERNAME, a.FIRSTNAME, a.LASTNAME, a.SHOWNNAME
from SchemaWema.users as a
WHERE (a.userdateupdated =
(SELECT MAX(b.userdateupdated) AS Expr1
FROM SchemaWema.users AS b
WHERE (a.userID = b.userID) ))
AND (a.RECORDSTATUS <> ''D'')
) Users on
VoterAnswers.VoterID = Users.USERID
AND Voter.VoterID = Users.USERID
inner join
(
SELECT DISTINCT AnswerID, QuestionID, AnswerText FROM SchemaWema.vts_tbAnswer AS a
WHERE (dateupdated =
(SELECT MAX(dateupdated) AS Expr1
FROM SchemaWema.vts_tbAnswer AS b
WHERE (a.AnswerID = AnswerID))) AND (recordstatus <> ''D'')
) Answer on
Answer.AnswerID = VoterAnswers.AnswerID
inner Join
(
SELECT DISTINCT QuestionID,SurveyID, QuestionText
FROM SchemaWema.vts_tbQuestion AS a
WHERE (dateupdated =
(SELECT MAX(dateupdated) AS Expr1
FROM SchemaWema.vts_tbQuestion AS b
WHERE (a.QuestionID = QuestionID))) AND (recordstatus <> ''D'')
) Question on
Answer.QuestionID = Question.QuestionID
AND Question.SurveyID = Survey.SurveyID
AND Question.SurveyID = VoterAnswers.SurveyID
inner join
(
SELECT DIStinct
[PANELID] ,[PANELNAME]
FROM [AdjudicateV3].[Adjudicate].[PROJECTPANELVIEW]
)Panel on
Panel.PANELID = Cases.PanelID
WHERE CASEs.ID = ' + #ID + ' AND Survey.DecisionSetId = '+ DeeSetId +' AND Survey.FormType = '+ #Forms +'
) AS SourceTable
PIVOT
(
MAX(AnswerText)
FOR QuestionText IN ('+#columns+')
) AS PivotTable'
It can be done using a dynamic pivot.
First thing you have to do is build the cols you're going to use for the pivot..
declare #cols varchar(max)
select #cols = Coalesce(#cols + ', ', '') + '[' + q.Question + '(' + a.Question + ')]'
from Questions q
join Answers a on q.ID = a.QuestionID
this will concatenate all of the column headers you want into one string like
[What is your favorite Car Color(Blue)], [What is your favorite Car Color(Red)]
putting the column names inside brackets is important here...
The next step is building your pivot query
declare #sql varchar(max)
set #sql = 'Select [User], ' + #cols + ' from (
select ua.[User], ''X'' as Chosen,
q.Question + ''('' + a.Question + '')'' Answer
from UserAnswers ua
join Answers a On ua.AnswerId = a.ID and ua.QuestionID = a.QuestionID
join Questions q on a.QuestionID = q.ID
) t
pivot (
max(Chosen)
for Answer IN (' + #cols + ')
) p'
exec(#sql)
this will create a subquery with three columns User, Chose, Answer.. user is user name, chosen is just an X for every record, and the Answer, which is what is used to pivot. Answer looks like the column names above without the brackets..
next it pivots the subquery.. and selects the Name and dynamic columns..
SQL Fiddle Example
The query below is working fine:
SELECT
tblCase.ID AS CaseID, tblCase.UserID AS MyCasesFilter,
tblGroupMembership.UserID AS GroupShareFilter,
tblDirectCaseSharing.ReceiverUserID AS DirectShareFilter, tblCase.EntryDate,
tblUser.LastName AS CaseAuthor, tblCase.Name AS CaseName,
COUNT(DISTINCT tblCaseImage.ID) AS TotalImages,
tblCaseType.Name AS CaseType, tblCase.SiteName, tblCase.Category,
tblCase.FollowUpDateTime, tblCase.Notes
FROM
tblDirectCaseSharing
RIGHT OUTER JOIN
tblCase
INNER JOIN tblUser ON tblCase.UserID = tblUser.ID ON tblDirectCaseSharing.CaseID = tblCase.ID
LEFT OUTER JOIN
tblGroupMembership
INNER JOIN
tblGroupCase ON tblGroupMembership.GroupID = tblGroupCase.GroupID ON tblCase.ID = tblGroupCase.CaseID
LEFT OUTER JOIN
tblCaseType ON tblCase.CaseTypeID = tblCaseType.ID
LEFT OUTER JOIN
tblCaseImage ON tblCase.ID = tblCaseImage.CaseID
GROUP BY
tblCase.ID, tblCaseType.Name, tblCase.SiteName, tblCase.EntryDate,
tblCase.Category, tblCase.FollowUpDateTime, tblCase.Notes, tblCase.UserID,
tblGroupMembership.UserID, tblDirectCaseSharing.ReceiverUserID,
tblUser.LastName, tblCase.Name
HAVING
(tblCase.UserID = 1)
AND (tblGroupMembership.UserID = 2)
AND (tblDirectCaseSharing.ReceiverUserID = 3)
ORDER BY
tblCase.EntryDate DESC
I want to add an additional select column to the above result using a select subquery which is:
STUFF((
SELECT ', ' +tblGroup.Name as [text()]
FROM tblCase INNER JOIN
tblGroupCase ON tblCase.ID = tblGroupCase.CaseID INNER JOIN
tblGroup ON tblGroupCase.GroupID = tblGroup.ID
WHERE tblCase.ID = ***
FOR XML PATH('')
),1,2,'')
AS ConcatGroupShares
The select subquery has a where clause and I need to get the tblcase.id which is the first column of the result set. how to i reference that value in the subquery.
Put an alias name in the main query
SELECT
tcase.ID AS CaseID, tblCase.UserID AS MyCasesFilter,
tblGroupMembership.UserID AS GroupShareFilter,
tblDirectCaseSharing.ReceiverUserID AS DirectShareFilter, tblCase.EntryDate,
tblUser.LastName AS CaseAuthor, tblCase.Name AS CaseName,
COUNT(DISTINCT tblCaseImage.ID) AS TotalImages,
tblCaseType.Name AS CaseType, tblCase.SiteName, tblCase.Category,
tblCase.FollowUpDateTime, tblCase.Notes
FROM
tblDirectCaseSharing
RIGHT OUTER JOIN
tblCase As tcase <=====
And use this alias name in the subquery:
STUFF((
SELECT ', ' +tblGroup.Name as [text()]
FROM tblCase INNER JOIN
tblGroupCase ON tblCase.ID = tblGroupCase.CaseID INNER JOIN
tblGroup ON tblGroupCase.GroupID = tblGroup.ID
WHERE tblCase.ID = tcase.id
FOR XML PATH('')
),1,2,'')
AS ConcatGroupShares
More about co-related sub-queries:
http://en.wikipedia.org/wiki/Correlated_subquery
This is a follow-up to #1644748 where I successfully answered my own question, but Quassnoi helped me to realize that it was the wrong question. He gave me a solution that worked for my sample data, but I couldn't plug it back into the parent stored procedure because I fail at SQL 2005 syntax. So here is an attempt to paint the broader picture and ask what I actually need.
This is part of a stored procedure that returns a list of items in a bug tracking application I've inherited. There are are over 100 fields and 26 joins so I'm pulling out only the mostly relevant bits.
SELECT
tickets.ticketid,
tickets.tickettype,
tickets_tickettype_lu.tickettypedesc,
tickets.stage,
tickets.position,
tickets.sponsor,
tickets.dev,
tickets.qa,
DATEDIFF(DAY, ticket_history_assignment.savedate, GETDATE()) as 'daysinqueue'
FROM
dbo.tickets WITH (NOLOCK)
LEFT OUTER JOIN dbo.tickets_tickettype_lu WITH (NOLOCK) ON tickets.tickettype = tickets_tickettype_lu.tickettypeid
LEFT OUTER JOIN dbo.tickets_history_assignment WITH (NOLOCK) ON tickets_history_assignment.ticketid = tickets.ticketid
AND tickets_history_assignment.historyid = (
SELECT
MAX(historyid)
FROM
dbo.tickets_history_assignment WITH (NOLOCK)
WHERE
tickets_history_assignment.ticketid = tickets.ticketid
GROUP BY
tickets_history_assignment.ticketid
)
WHERE
tickets.sponsor = #sponsor
The area of interest is the daysinqueue subquery mess. The tickets_history_assignment table looks roughly as follows
declare #tickets_history_assignment table (
historyid int,
ticketid int,
sponsor int,
dev int,
qa int,
savedate datetime
)
insert into #tickets_history_assignment values (1521402, 92774,20,14, 20, '2009-10-27 09:17:59.527')
insert into #tickets_history_assignment values (1521399, 92774,20,14, 42, '2009-08-31 12:07:52.917')
insert into #tickets_history_assignment values (1521311, 92774,100,14, 42, '2008-12-08 16:15:49.887')
insert into #tickets_history_assignment values (1521336, 92774,100,14, 42, '2009-01-16 14:27:43.577')
Whenever a ticket is saved, the current values for sponsor, dev and qa are stored in the tickets_history_assignment table with the ticketid and a timestamp. So it is possible for someone to change the value for qa, but leave sponsor alone.
What I want to know, based on all of these conditions, is the historyid of the record in the tickets_history_assignment table where the sponsor value was last changed so that I can calculate the value for daysinqueue. If a record is inserted into the history table, and only the qa value has changed, I don't want that record. So simply relying on MAX(historyid) won't work for me.
Quassnoi came up with the following which seemed to work with my sample data, but I can't plug it into the larger query, SQL Manager bitches about the WITH statement.
;WITH rows AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY ticketid ORDER BY savedate DESC) AS rn
FROM #Table
)
SELECT rl.sponsor, ro.savedate
FROM rows rl
CROSS APPLY
(
SELECT TOP 1 rc.savedate
FROM rows rc
JOIN rows rn
ON rn.ticketid = rc.ticketid
AND rn.rn = rc.rn + 1
AND rn.sponsor <> rc.sponsor
WHERE rc.ticketid = rl.ticketid
ORDER BY
rc.rn
) ro
WHERE rl.rn = 1
I played with it yesterday afternoon and got nowhere because I don't fundamentally understand what is going on here and how it should fit into the larger context.
So, any takers?
UPDATE
Ok, here's the whole thing. I've been switching some of the table and column names in an attempt to simplify things so here's the full unedited mess.
snip - old bad code
Here are the errors:
Msg 102, Level 15, State 1, Procedure usp_GetProjectRecordsByAssignment, Line 159
Incorrect syntax near ';'.
Msg 102, Level 15, State 1, Procedure usp_GetProjectRecordsByAssignment, Line 179
Incorrect syntax near ')'.
Line numbers are of course not correct but refer to
;WITH rows AS
And the ')' char after the WHERE rl.rn = 1
)
Respectively
Is there a tag for extra super long question?
UPDATE #2
Here is the finished query for anyone who may need this:
CREATE PROCEDURE [dbo].[usp_GetProjectRecordsByAssignment]
(
#assigned numeric(18,0),
#assignedtype numeric(18,0)
)
AS
SET NOCOUNT ON
WITH rows AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY recordid ORDER BY savedate DESC) AS rn
FROM projects_history_assignment
)
SELECT projects_records.recordid,
projects_records.recordtype,
projects_recordtype_lu.recordtypedesc,
projects_records.stage,
projects_stage_lu.stagedesc,
projects_records.position,
projects_position_lu.positiondesc,
CASE projects_records.clientrequested
WHEN '1' THEN 'Yes'
WHEN '0' THEN 'No'
END AS clientrequested,
projects_records.reportingmethod,
projects_reportingmethod_lu.reportingmethoddesc,
projects_records.clientaccess,
projects_clientaccess_lu.clientaccessdesc,
projects_records.clientnumber,
projects_records.project,
projects_lu.projectdesc,
projects_records.version,
projects_version_lu.versiondesc,
projects_records.projectedversion,
projects_version_lu_projected.versiondesc AS projectedversiondesc,
projects_records.sitetype,
projects_sitetype_lu.sitetypedesc,
projects_records.title,
projects_records.module,
projects_module_lu.moduledesc,
projects_records.component,
projects_component_lu.componentdesc,
projects_records.loginusername,
projects_records.loginpassword,
projects_records.assistedusername,
projects_records.browsername,
projects_browsername_lu.browsernamedesc,
projects_records.browserversion,
projects_records.osname,
projects_osname_lu.osnamedesc,
projects_records.osversion,
projects_records.errortype,
projects_errortype_lu.errortypedesc,
projects_records.gsipriority,
projects_gsipriority_lu.gsiprioritydesc,
projects_records.clientpriority,
projects_clientpriority_lu.clientprioritydesc,
projects_records.scheduledstartdate,
projects_records.scheduledcompletiondate,
projects_records.projectedhours,
projects_records.actualstartdate,
projects_records.actualcompletiondate,
projects_records.actualhours,
CASE projects_records.billclient
WHEN '1' THEN 'Yes'
WHEN '0' THEN 'No'
END AS billclient,
projects_records.billamount,
projects_records.status,
projects_status_lu.statusdesc,
CASE CAST(projects_records.assigned AS VARCHAR(5))
WHEN '0' THEN 'N/A'
WHEN '10000' THEN 'Unassigned'
WHEN '20000' THEN 'Client'
WHEN '30000' THEN 'Tech Support'
WHEN '40000' THEN 'LMI Tech Support'
WHEN '50000' THEN 'Upload'
WHEN '60000' THEN 'Spider'
WHEN '70000' THEN 'DB Admin'
ELSE rtrim(users_assigned.nickname) + ' ' + rtrim(users_assigned.lastname)
END AS assigned,
CASE CAST(projects_records.assigneddev AS VARCHAR(5))
WHEN '0' THEN 'N/A'
WHEN '10000' THEN 'Unassigned'
ELSE rtrim(users_assigneddev.nickname) + ' ' + rtrim(users_assigneddev.lastname)
END AS assigneddev,
CASE CAST(projects_records.assignedqa AS VARCHAR(5))
WHEN '0' THEN 'N/A'
WHEN '10000' THEN 'Unassigned'
ELSE rtrim(users_assignedqa.nickname) + ' ' + rtrim(users_assignedqa.lastname)
END AS assignedqa,
CASE CAST(projects_records.assignedsponsor AS VARCHAR(5))
WHEN '0' THEN 'N/A'
WHEN '10000' THEN 'Unassigned'
ELSE rtrim(users_assignedsponsor.nickname) + ' ' + rtrim(users_assignedsponsor.lastname)
END AS assignedsponsor,
projects_records.clientcreated,
CASE projects_records.clientcreated
WHEN '1' THEN 'Yes'
WHEN '0' THEN 'No'
END AS clientcreateddesc,
CASE projects_records.clientcreated
WHEN '1' THEN rtrim(clientusers_createuser.firstname) + ' ' + rtrim(clientusers_createuser.lastname) + ' (Client)'
ELSE rtrim(users_createuser.nickname) + ' ' + rtrim(users_createuser.lastname)
END AS createuser,
projects_records.createdate,
projects_records.savedate,
projects_resolution.sitesaffected,
projects_sitesaffected_lu.sitesaffecteddesc,
DATEDIFF(DAY, projects_history_assignment.savedate, GETDATE()) as 'daysinqueue',
projects_records.iOnHitList,
projects_records.changetype
FROM
dbo.projects_records WITH (NOLOCK)
LEFT OUTER JOIN dbo.projects_recordtype_lu WITH (NOLOCK) ON projects_records.recordtype = projects_recordtype_lu.recordtypeid
LEFT OUTER JOIN dbo.projects_stage_lu WITH (NOLOCK) ON projects_records.stage = projects_stage_lu.stageid
LEFT OUTER JOIN dbo.projects_position_lu WITH (NOLOCK) ON projects_records.position = projects_position_lu.positionid
LEFT OUTER JOIN dbo.projects_reportingmethod_lu WITH (NOLOCK) ON projects_records.reportingmethod = projects_reportingmethod_lu.reportingmethodid
LEFT OUTER JOIN dbo.projects_lu WITH (NOLOCK) ON projects_records.project = projects_lu.projectid
LEFT OUTER JOIN dbo.projects_version_lu WITH (NOLOCK) ON projects_records.version = projects_version_lu.versionid
LEFT OUTER JOIN dbo.projects_version_lu projects_version_lu_projected WITH (NOLOCK) ON projects_records.projectedversion = projects_version_lu_projected.versionid
LEFT OUTER JOIN dbo.projects_sitetype_lu WITH (NOLOCK) ON projects_records.sitetype = projects_sitetype_lu.sitetypeid
LEFT OUTER JOIN dbo.projects_module_lu WITH (NOLOCK) ON projects_records.module = projects_module_lu.moduleid
LEFT OUTER JOIN dbo.projects_component_lu WITH (NOLOCK) ON projects_records.component = projects_component_lu.componentid
LEFT OUTER JOIN dbo.projects_browsername_lu WITH (NOLOCK) ON projects_records.browsername = projects_browsername_lu.browsernameid
LEFT OUTER JOIN dbo.projects_osname_lu WITH (NOLOCK) ON projects_records.osname = projects_osname_lu.osnameid
LEFT OUTER JOIN dbo.projects_errortype_lu WITH (NOLOCK) ON projects_records.errortype = projects_errortype_lu.errortypeid
LEFT OUTER JOIN dbo.projects_resolution WITH (NOLOCK) ON projects_records.recordid = projects_resolution.recordid
LEFT OUTER JOIN dbo.projects_sitesaffected_lu WITH (NOLOCK) ON projects_resolution.sitesaffected = projects_sitesaffected_lu.sitesaffectedid
LEFT OUTER JOIN dbo.projects_gsipriority_lu WITH (NOLOCK) ON projects_records.gsipriority = projects_gsipriority_lu.gsipriorityid
LEFT OUTER JOIN dbo.projects_clientpriority_lu WITH (NOLOCK) ON projects_records.clientpriority = projects_clientpriority_lu.clientpriorityid
LEFT OUTER JOIN dbo.projects_status_lu WITH (NOLOCK) ON projects_records.status = projects_status_lu.statusid
LEFT OUTER JOIN dbo.projects_clientaccess_lu WITH (NOLOCK) ON projects_records.clientaccess = projects_clientaccess_lu.clientaccessid
LEFT OUTER JOIN dbo.users users_assigned WITH (NOLOCK) ON projects_records.assigned = users_assigned.userid
LEFT OUTER JOIN dbo.users users_assigneddev WITH (NOLOCK) ON projects_records.assigneddev = users_assigneddev.userid
LEFT OUTER JOIN dbo.users users_assignedqa WITH (NOLOCK) ON projects_records.assignedqa = users_assignedqa.userid
LEFT OUTER JOIN dbo.users users_assignedsponsor WITH (NOLOCK) ON projects_records.assignedsponsor = users_assignedsponsor.userid
LEFT OUTER JOIN dbo.users users_createuser WITH (NOLOCK) ON projects_records.createuser = users_createuser.userid
LEFT OUTER JOIN dbo.clientusers clientusers_createuser WITH (NOLOCK) ON projects_records.createuser = clientusers_createuser.userid
LEFT OUTER JOIN dbo.projects_history_assignment WITH (NOLOCK) ON projects_history_assignment.recordid = projects_records.recordid
AND projects_history_assignment.historyid = (
SELECT ro.historyid
FROM rows rl
CROSS APPLY
(
SELECT TOP 1 rc.historyid
FROM rows rc
JOIN rows rn
ON rn.recordid = rc.recordid
AND rn.rn = rc.rn + 1
AND rn.assigned <> rc.assigned
WHERE rc.recordid = rl.recordid
ORDER BY
rc.rn
) ro
WHERE rl.rn = 1
AND rl.recordid = projects_records.recordid
)
WHERE
(#assignedtype='0' and projects_records.assigned = #assigned)
OR (#assignedtype='1' and projects_records.assigneddev = #assigned)
OR (#assignedtype='2' and projects_records.assignedqa = #assigned)
OR (#assignedtype='3' and projects_records.assignedsponsor = #assigned)
OR (#assignedtype='4' and projects_records.createuser = #assigned)
WITH rows AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY ticketid ORDER BY savedate DESC) AS rn
FROM #Table
)
SELECT projects_records.recordid,
projects_records.recordtype,
/* skipped */
AND projects_history_assignment.historyid = (
SELECT ro.historyid
FROM rows rl
CROSS APPLY
(
SELECT TOP 1 rc.savedate
FROM rows rc
JOIN rows rn
ON rn.recordid = rc.recordid
AND rn.rn = rc.rn + 1
AND rn.assigned <> rc.assigned
WHERE rc.recordid = rl.recordid
ORDER BY
rc.rn
) ro
WHERE rl.rn = 1
AND rl.recordid = projects_records.recordid
)
Well, if that query does not work out -- you could always consider a trigger on the tickets_history_assignment table. You could use INSTEAD OF INSERT, UPDATE which fires before any changes are made, so you would have full control of what is about to change and what to do.