Forum Discussion
SqlPuzzle
Dec 03, 2024Copper Contributor
sql query to check status change of an item
I have a table dbo.tblPresentationStatus (sql script at the bottom ) I have to select rows where the status change is wrong. Flow should be as this: Review --> approve --> presentation --> close F...
rodgerkong
Dec 03, 2024Iron Contributor
- Create a table with Table Value Constructor to assign a int value to Status string. The table named SI, Column I is the int value.
- Use CTE create a dataset which contains 2 column calculated from window function. One column contains sequence values partition by PrID which named SN. Another one contains the difference of I between current row and the previous row which named Diff.
- Column SN will be used to construct PIVOT table. Obviously, the row with Diff value negative or zero has issue.
- Filter all PrID that have Diff issue, and PIVOT them by SN will get result.
Here is code
WITH C --CTE table
AS
(
SELECT PS.*, SI.I
, ROW_NUMBER() OVER (PARTITION BY PS.PrID ORDER BY StatusID) AS SN --Will used in PIVOT
, SI.I - LAG(SI.I, 1, 0) OVER (PARTITION BY PS.PrID ORDER BY StatusID) AS Diff --Find row has issue
FROM
(VALUES(1, 'REVIEW'), (2, 'APPROVE'), (3, 'PRESENTATION'), (4, 'CLOSE')) AS SI(I, S) --Assign int value to status
INNER JOIN #tblPresentationStatus PS
ON PS.PrStatus = SI.S
)
SELECT
PrID,
[1] AS [Status1],
[2] AS [Status2],
[3] AS [Status3],
[4] AS [Status4]
FROM
(
SELECT PrID, PrStatus, SN
FROM
C WHERE PrID IN
( SELECT PrID FROM C WHERE Diff<=0 ) --Get PrID that has issue
)D
PIVOT
(
MIN(PrStatus) FOR SN IN ([1],[2],[3],[4])
)PP