Skip to content
Advertisement

Grouping rows over common data in a column and min max start/end date via cursor fetch method

I have a stored procedure with a couple of input parameters

Input parameters:

Result set:

AuxTable is not the final intended table, it’s just being displayed for debugging/troubleshooting.

MsgLinkId MyRowId WO_ID SourceUnitName MaterialName BatchID UnitofMeasure Segment1 Segment2 Segment3 Segment4 Segment5 Amount StartDate EndDate
5 1 731000037 B1S01C03 RAW MILK 0 KGM B1S01W32 NONE NONE NONE NONE 13391.7524414063 2022-01-01 14:22:25.773 2022-01-01 14:24:25.980
5 2 731000037 B1S01C03 RAW MILK 0 KGM B1S01W32 NONE NONE NONE NONE 13391.7524414063 2022-01-01 14:22:25.773 2022-01-01 14:26:26.187
5 3 731000037 B1S01C03 RAW MILK 0 KGM B1S01W32 NONE NONE NONE NONE 13391.7524414063 2022-01-01 14:22:25.773 2022-01-01 14:28:26.397
7 1 732000049 B1S01C03 RAW MILK 0 KGM B1S01W32 NONE NONE NONE NONE 31993.4200439453 2022-01-02 17:12:43.550 2022-01-02 17:14:43.757
7 2 732000049 B1S01C03 RAW MILK 0 KGM B1S01W32 NONE NONE NONE NONE 31993.4200439453 2022-01-02 17:12:43.550 2022-01-02 17:16:43.967
7 3 732000049 B1S01C03 RAW MILK 0 KGM B1S01W32 NONE NONE NONE NONE 31993.4200439453 2022-01-02 17:12:43.550 2022-01-02 17:18:44.177
3 1 732000049 B1S01C04 RAW MILK 0 KGM B1S01W32 NONE NONE NONE NONE 57417.6939544678 2022-01-02 15:48:17.530 2022-01-02 15:50:17.737
3 2 732000049 B1S01C04 RAW MILK 0 KGM B1S01W32 NONE NONE NONE NONE 57417.6939544678 2022-01-02 15:48:17.530 2022-01-02 15:52:17.947
3 3 732000049 B1S01C04 RAW MILK 0 KGM B1S01W32 NONE NONE NONE NONE 57417.6939544678 2022-01-02 15:48:17.530 2022-01-02 15:54:18.157

FinalTable:

Unit_WO SourceUnitName MaterialName BatchID UnitofMeasure Segment1 Segment2 Segment3 Segment4 Segment5 Amount StartDate EndDate
731000037 B1S01C03 RAW MILK 0 KGM B1S01W32 NONE NONE NONE NONE 13391.75 2022-01-01 14:22:25.773 2022-01-01 14:43:09.060
732000049 B1S01C03 RAW MILK 0 KGM B1S01W32 NONE NONE NONE NONE 31993.42 2022-01-02 17:12:43.550 2022-01-02 17:57:51.643
732000049 B1S01C04 RAW MILK 0 KGM B1S01W32 NONE NONE NONE NONE 57417.7 2022-01-02 15:48:17.530 2022-01-02 17:12:40.333

This is just a sample to understand the situation.

Question: how can I get “FinalTable”, without using the cursor fetch method?

I have tried using max(Amount), min(Start date), max(End date) and tried grouping over MsgLinkId,MyRowId but it didn’t work.

This is my stored procedure:

Advertisement

Answer

Based on what the cursor appears to be doing, the below cte query should get your results. It appears the cursor is inserting the first MsgLinkId record (MyRowID = 1) and then updating the EndDate for any subsequent record. This query takes the first MsgLinkId record and joins to the last MsgLinkId record in order to take the EndDate, but retains all the other data from the first record.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement