Forum Discussion
Martin_Kevin
Aug 07, 2024Copper Contributor
Help to find in sequence issue in groups records
Hi, Every group_cost has different sequence of PP_Seq but it should not be any gap in the sequence of any group_cost rcords. It should always be increment by 1. I want to see any record/row of any gr...
- Aug 08, 2024
1. Add a continued sequence with ROW_NUMBER, named PP_seq_correct;
2. Calculate differences of PP_seq and PP_seq_correct, get the difference of first element in each group_cost set as stand value.
3. Filter the rows that the differences not equal the stand value, they are all incorrect.
4. Get the first row from the incorrect rows grouping by group_cost.
WITH T (group_cost, PP_Seq, Seq_no, diff) AS ( SELECT c.group_cost, c.PP_seq, a.PP_seq_correct, c.PP_seq-a.PP_seq_correct AS diff FROM #Cost c INNER JOIN ( SELECT group_cost, PP_Seq, ROW_NUMBER() OVER(PARTITION BY group_cost ORDER BY PP_seq) AS PP_seq_correct FROM #Cost ) a ON c.group_cost=a.group_cost AND c.PP_seq=a.PP_seq ) SELECT Co.*, 'Comments...' Comments FROM #cost Co INNER JOIN ( SELECT T.group_cost, Min(PP_Seq) PP_Seq FROM T LEFT JOIN ( SELECT T.group_cost, T.diff FROM T WHERE T.seq_no=1 ) D ON T.group_cost=D.group_cost AND T.diff=D.Diff WHERE D.diff IS NULL GROUP BY T.group_cost )R ON Co.group_cost=R.group_cost AND Co.PP_Seq=R.PP_Seq
rodgerkong
Aug 08, 2024Iron Contributor
1. Add a continued sequence with ROW_NUMBER, named PP_seq_correct;
2. Calculate differences of PP_seq and PP_seq_correct, get the difference of first element in each group_cost set as stand value.
3. Filter the rows that the differences not equal the stand value, they are all incorrect.
4. Get the first row from the incorrect rows grouping by group_cost.
WITH T (group_cost, PP_Seq, Seq_no, diff) AS
(
SELECT c.group_cost, c.PP_seq, a.PP_seq_correct, c.PP_seq-a.PP_seq_correct AS diff
FROM #Cost c
INNER JOIN
(
SELECT group_cost, PP_Seq, ROW_NUMBER() OVER(PARTITION BY group_cost ORDER BY PP_seq) AS PP_seq_correct FROM #Cost
) a
ON c.group_cost=a.group_cost AND c.PP_seq=a.PP_seq
)
SELECT Co.*, 'Comments...' Comments FROM #cost Co INNER JOIN
(
SELECT T.group_cost, Min(PP_Seq) PP_Seq FROM T LEFT JOIN
(
SELECT T.group_cost, T.diff FROM T WHERE T.seq_no=1
) D
ON T.group_cost=D.group_cost AND T.diff=D.Diff
WHERE D.diff IS NULL
GROUP BY T.group_cost
)R
ON Co.group_cost=R.group_cost AND Co.PP_Seq=R.PP_Seq
Martin_Kevin
Aug 10, 2024Copper Contributor
rodgerkong Thanks a lot