Review ask

As a clinical trial statistician or programmer, challenge anything in this benchmark: describe a problem in Comments, or propose a fix with the Edit button on any source file.

  1. Task: Would a real study need this derivation, specified this way? Does it follow CDISC SDTM: variable names, controlled terms, record structure? Flag any rule that is ambiguous or that a sponsor would handle differently.
  2. Inputs: Do they look like data collected in a real trial, and do they include the situations you would expect to meet in one?
  3. Expected output: Would independent QC programming reproduce every value from these inputs and rules?

The other tabs beside Comments are background for assessment, not under review.

Summary

Lifecycle: draftEditUnder review
What this benchmark means
README.md

Goal: build the SDTM subject visits (SV) domain from Operational Data Model (ODM) item data plus a demographics (DM) extract, naming for each visit the study events its subjects attended, when each visit started and ended, and the planned day, order, and epoch it belongs to.

Input: an ODM extract, one row per item value with the columns StudyOID, MetaDataVersionOID, SubjectKey, StudyEventOID, StudyEventRepeatKey, ItemGroupOID, ItemGroupRepeatKey, ItemOID and Value; plus a small DM extract with STUDYID, USUBJID and the reference start date RFSTDTC. Each study event carries its planned-visit attributes (visit name, visit number, planned day, planned order, epoch) as ODM items, and the VS, LB and EX forms carry their own collection dates.

Variables:

  • SVSEQ numbers each subject's visits in date order.
  • VISIT is the visit name carried on the study event, e.g. Week 2.
  • VISITNUM is the planned visit number. Distinct numbers starting at 99.1 identify a subject's unscheduled visits.
  • VISITDY is the planned study day of the visit; it stays empty for unscheduled visits, which carry no plan.
  • SVSTDTC is the start date of the visit, the earliest form date among the visit's VS, LB and EX forms.
  • SVENDTC is the end date of the visit, the latest form date; a visit whose forms were collected on different days spans them.
  • SVSTDY is the study day of the visit start, counted from the subject's RFSTDTC.
  • SVENDY is the study day of the visit end, counted from the subject's RFSTDTC.
  • TAETORD is the planned order of the element within the arm; it stays empty for unscheduled visits.
  • EPOCH is the epoch carried on the study event, e.g. TREATMENT.
  • SVUPDES is the description the site entered for the unplanned visit, carried on the unscheduled study event as an ODM item; it stays empty for planned visits.

Note: visits are numbered by their start date, so an unscheduled visit takes its place between the planned visits around it. Repeated unscheduled visits retain separate identities.

Provenance: the fixtures are hand-built from a realistic EDC visit flow with plausible ODM naming, not records from a real study.

Inputs

Under review
2 source files

input/dm.csv

Edit
2 rows
input/dm.csv
STUDYIDUSUBJIDRFSTDTC
YAMAA-012026-02-17
YAMAA-012026-02-18

input/odm.csv

Edit
54 rows
input/odm.csv
StudyOIDMetaDataVersionOIDSubjectKeyStudyEventOIDStudyEventRepeatKeyItemGroupOIDItemGroupRepeatKeyItemOIDValue
YAMAA-01MDV.1001SCRN1IG.TV1IT.TV.VISITScreening
YAMAA-01MDV.1001SCRN1IG.TV1IT.TV.VISITNUM-1
YAMAA-01MDV.1001SCRN1IG.TV1IT.TV.VISITDY-7
YAMAA-01MDV.1001SCRN1IG.TV1IT.TV.TAETORD1
YAMAA-01MDV.1001SCRN1IG.TV1IT.TV.EPOCHSCREENING
YAMAA-01MDV.1001SCRN1IG.VS1IT.VS.VSDTC2026-02-10
YAMAA-01MDV.1001BL1IG.TV1IT.TV.VISITBaseline
YAMAA-01MDV.1001BL1IG.TV1IT.TV.VISITNUM1
YAMAA-01MDV.1001BL1IG.TV1IT.TV.VISITDY1
YAMAA-01MDV.1001BL1IG.TV1IT.TV.TAETORD2
YAMAA-01MDV.1001BL1IG.TV1IT.TV.EPOCHTREATMENT
YAMAA-01MDV.1001BL1IG.VS1IT.VS.VSDTC2026-02-17
YAMAA-01MDV.1001BL1IG.LB1IT.LB.LBDTC2026-02-17
YAMAA-01MDV.1001BL1IG.EX1IT.EX.EXDTC2026-02-17
YAMAA-01MDV.1001UNSCH1IG.TV1IT.TV.VISITUnscheduled
YAMAA-01MDV.1001UNSCH1IG.TV1IT.TV.VISITNUM99.1
YAMAA-01MDV.1001UNSCH1IG.TV1IT.TV.UPDESUnscheduled safety visit
YAMAA-01MDV.1001UNSCH1IG.TV1IT.TV.EPOCHTREATMENT
YAMAA-01MDV.1001UNSCH1IG.VS1IT.VS.VSDTC2026-03-02
YAMAA-01MDV.1001UNSCH2IG.TV1IT.TV.VISITUnscheduled
YAMAA-01MDV.1001UNSCH2IG.TV1IT.TV.VISITNUM99.2
YAMAA-01MDV.1001UNSCH2IG.TV1IT.TV.UPDESUnscheduled follow-up visit
YAMAA-01MDV.1001UNSCH2IG.TV1IT.TV.EPOCHTREATMENT
YAMAA-01MDV.1001UNSCH2IG.VS1IT.VS.VSDTC2026-03-04
YAMAA-01MDV.1001W21IG.TV1IT.TV.VISITWeek 2
YAMAA-01MDV.1001W21IG.TV1IT.TV.VISITNUM2
YAMAA-01MDV.1001W21IG.TV1IT.TV.VISITDY15
YAMAA-01MDV.1001W21IG.TV1IT.TV.TAETORD3
YAMAA-01MDV.1001W21IG.TV1IT.TV.EPOCHTREATMENT
YAMAA-01MDV.1001W21IG.VS1IT.VS.VSDTC2026-03-05
YAMAA-01MDV.1001W21IG.LB1IT.LB.LBDTC2026-03-06
YAMAA-01MDV.1001W21IG.EX1IT.EX.EXDTC2026-03-05
YAMAA-01MDV.1002SCRN1IG.TV1IT.TV.VISITScreening
YAMAA-01MDV.1002SCRN1IG.TV1IT.TV.VISITNUM-1
YAMAA-01MDV.1002SCRN1IG.TV1IT.TV.VISITDY-7
YAMAA-01MDV.1002SCRN1IG.TV1IT.TV.TAETORD1
YAMAA-01MDV.1002SCRN1IG.TV1IT.TV.EPOCHSCREENING
YAMAA-01MDV.1002SCRN1IG.VS1IT.VS.VSDTC2026-02-11
YAMAA-01MDV.1002BL1IG.TV1IT.TV.VISITBaseline
YAMAA-01MDV.1002BL1IG.TV1IT.TV.VISITNUM1
YAMAA-01MDV.1002BL1IG.TV1IT.TV.VISITDY1
YAMAA-01MDV.1002BL1IG.TV1IT.TV.TAETORD2
YAMAA-01MDV.1002BL1IG.TV1IT.TV.EPOCHTREATMENT
YAMAA-01MDV.1002BL1IG.VS1IT.VS.VSDTC2026-02-18
YAMAA-01MDV.1002BL1IG.LB1IT.LB.LBDTC2026-02-18
YAMAA-01MDV.1002BL1IG.EX1IT.EX.EXDTC2026-02-18
YAMAA-01MDV.1002W21IG.TV1IT.TV.VISITWeek 2
YAMAA-01MDV.1002W21IG.TV1IT.TV.VISITNUM2
YAMAA-01MDV.1002W21IG.TV1IT.TV.VISITDY15
YAMAA-01MDV.1002W21IG.TV1IT.TV.TAETORD3
YAMAA-01MDV.1002W21IG.TV1IT.TV.EPOCHTREATMENT
YAMAA-01MDV.1002W21IG.VS1IT.VS.VSDTC2026-03-07
YAMAA-01MDV.1002W21IG.LB1IT.LB.LBDTC2026-03-07
YAMAA-01MDV.1002W21IG.EX1IT.EX.EXDTC2026-03-07

Expected output

Under review
8 expected rows

expected/sv.csv

Edit
8 rows
expected/sv.csv
DOMAINSTUDYIDUSUBJIDSVSEQVISITVISITNUMVISITDYSVSTDTCSVENDTCSVSTDYSVENDYTAETORDEPOCHSVUPDES
SVYAMAA-011Screening-1-72026-02-102026-02-10-7-71SCREENING—
SVYAMAA-012Baseline112026-02-172026-02-17112TREATMENT—
SVYAMAA-013Unscheduled99.1—2026-03-022026-03-021414—TREATMENTUnscheduled safety visit
SVYAMAA-014Unscheduled99.2—2026-03-042026-03-041616—TREATMENTUnscheduled follow-up visit
SVYAMAA-015Week 22152026-03-052026-03-0617183TREATMENT—
SVYAMAA-011Screening-1-72026-02-112026-02-11-7-71SCREENING—
SVYAMAA-012Baseline112026-02-182026-02-18112TREATMENT—
SVYAMAA-013Week 22152026-03-072026-03-0718183TREATMENT—
Shaded columns are derived— = missing value

Comments and assessment materials

Comments

Signed in with GitHub; saved in repository Discussions

Mapping spec

Generated from the benchmark YAML; do not edit by hand

Variable NameVariable LabelTypeLengthControlled Terms or FormatOriginCoreConversion DefinitionVariable TypeVariable OrderComments for Define
DOMAINDomain AbbreviationCharAssignedSet constant value "SV".SDTM1
STUDYIDStudy IdentifierCharCollectedCopy value from ODM.StudyOID.SDTM2
USUBJIDUnique Subject IdentifierCharCollectedCopy value from ODM.SubjectKey.SDTM3
VISITVisit NameCharDerivedSet per constructed row; see the Row construction sheet.SDTM4
VISITNUMVisit NumberNumDerivedSet per constructed row; see the Row construction sheet.SDTM5
VISITDYPlanned Study Day of VisitNumDerivedSet per constructed row; see the Row construction sheet.SDTM6
SVSTDTCStart Date/Time of VisitCharISO 8601DerivedLeast of VSDTC, LBDTC and EXDTC.SDTM7
SVENDTCEnd Date/Time of VisitCharISO 8601DerivedGreatest of VSDTC, LBDTC and EXDTC.SDTM8
SVSTDYStudy Day of Start of VisitNumDerivedCDISC study day of SVSTDTC against RFSTDTC as day 1; there is no day zero.SDTM9
SVENDYStudy Day of End of VisitNumDerivedCDISC study day of SVENDTC against RFSTDTC as day 1; there is no day zero.SDTM10
TAETORDPlanned Order of Element within ArmNumDerivedSet per constructed row; see the Row construction sheet.SDTM11
EPOCHEpochCharDerivedSet per constructed row; see the Row construction sheet.SDTM12
SVUPDESDescription of Unplanned VisitCharDerivedSet per constructed row; see the Row construction sheet.SDTM13
SVSEQSequence NumberNumDerivedRow number within each group of STUDYID, USUBJID, ordered by SVSTDTC.SDTM14
TemplateInclude whenVISITVISITNUMVISITDYVSDTCLBDTCEXDTCTAETORDEPOCHSVUPDES
visitAggregate ONLY(ODM.Value) over records matching on the shared output keys, where ODM.ItemOID = 'IT.TV.VISIT'Aggregate ONLY(ODM.Value) over records matching on the shared output keys, where ODM.ItemOID = 'IT.TV.VISITNUM'Aggregate ONLY(ODM.Value) over records matching on the shared output keys, where ODM.ItemOID = 'IT.TV.VISITDY'Aggregate ONLY(ODM.Value) over records matching on the shared output keys, where ODM.ItemOID = 'IT.VS.VSDTC'Aggregate ONLY(ODM.Value) over records matching on the shared output keys, where ODM.ItemOID = 'IT.LB.LBDTC'Aggregate ONLY(ODM.Value) over records matching on the shared output keys, where ODM.ItemOID = 'IT.EX.EXDTC'Aggregate ONLY(ODM.Value) over records matching on the shared output keys, where ODM.ItemOID = 'IT.TV.TAETORD'Aggregate ONLY(ODM.Value) over records matching on the shared output keys, where ODM.ItemOID = 'IT.TV.EPOCH'Aggregate ONLY(ODM.Value) over records matching on the shared output keys, where ODM.ItemOID = 'IT.TV.UPDES'
VersionDateAuthorDescriptionReviewerSign-off
1.32026-09-29yamaa docs buildShow study codelist names, external dictionaries, and ISO 8601 formats in variable rows; list the document's codelist values and metadata
1.22026-09-29yamaa docs buildClassify ADaM copies from a declared input as Predecessor and recodes as Derived, and SDTM recodes of locally derived columns as Derived
1.12026-09-29yamaa docs buildResolve lookups into the donor record they select, and give every derivation shape a plain-language rule instead of its raw YAML
1.0yamaa docs buildInitial generation from spec.yaml

Agent prompt

The request an agent receives with the input files; each tier states no more than the one above

prompts/sdtm-sv-subject-visits/full.md

Edit
31 lines

Following CDISC SDTM standards, use the provided DM and ODM datasets to create an SV dataset with one record per subject per visit attended.

The output dataset should contain the following columns in this order: DOMAIN, STUDYID, USUBJID, SVSEQ, VISIT, VISITNUM, VISITDY, SVSTDTC, SVENDTC, SVSTDY, SVENDY, TAETORD, EPOCH, SVUPDES

STUDYID is the ODM StudyOID and USUBJID is the SubjectKey, each as given.

SVSEQ numbers each subject's visits in date order. VISIT is the visit name carried on the study event. VISITNUM is the planned visit number; distinct numbers starting at 99.1 identify a subject's unscheduled visits. VISITDY is the planned study day of the visit, and has no value for unscheduled visits. TAETORD is the planned order of the element within the arm, and has no value for unscheduled visits. EPOCH is the epoch carried on the study event.

SVSTDTC is the start date of the visit, the earliest form date among the visit's VS, LB, and EX forms; SVENDTC is the end date, the latest form date. A visit whose forms were collected on different days spans them. SVSTDY and SVENDY are the study days of the visit start and end, counted from the subject's reference start date with that date as day 1 and no day zero. SVUPDES is the description the site entered for the unplanned visit, and has no value for planned visits.

Visits are numbered by their start date, so an unscheduled visit takes its place between the planned visits around it. Repeated unscheduled visits retain separate identities.

Read the source datasets from /app/input and save the completed dataset as /app/output/sv.csv.

prompts/sdtm-sv-subject-visits/conventions.md

Edit
12 lines

Following CDISC SDTM standards, use the provided DM and ODM datasets to create an SV dataset with one record per subject per visit attended.

The output dataset should contain the following columns in this order: DOMAIN, STUDYID, USUBJID, SVSEQ, VISIT, VISITNUM, VISITDY, SVSTDTC, SVENDTC, SVSTDY, SVENDY, TAETORD, EPOCH, SVUPDES

VISITNUM is the planned visit number; distinct numbers starting at 99.1 identify a subject's unscheduled visits.

Read the source datasets from /app/input and save the completed dataset as /app/output/sv.csv.

prompts/sdtm-sv-subject-visits/brief.md

Edit
9 lines

Following CDISC SDTM standards, use the provided DM and ODM datasets to create an SV dataset with one record per subject per visit attended.

The output dataset should contain the following columns in this order: DOMAIN, STUDYID, USUBJID, SVSEQ, VISIT, VISITNUM, VISITDY, SVSTDTC, SVENDTC, SVSTDY, SVENDY, TAETORD, EPOCH, SVUPDES

Read the source datasets from /app/input and save the completed dataset as /app/output/sv.csv.

yamaa code

Runs the yamaa specification; its result must match the expected output

run.R

Edit
4 lines
library(yamaa)sv <- yamaa_domain("spec.yaml")$outputsv

run.py

Edit
4 lines
import yamaasv = yamaa.yamaa_domain("spec.yaml").outputsv

Solution without yamaa

Written from the full prompt and the inputs alone; CI checks it reproduces the expected output

solutions/sdtm-sv-subject-visits/result.R

Edit
79 lines
# Reference solution for the yamaa benchmark sdtm-sv-subject-visits (R track).## Written from the benchmark's full prompt and its inputs alone, as an agent# would write it. Harbor's oracle agent runs it to check that the prompt can# be solved and that the grader scores a correct answer 1.library(dplyr, warn.conflicts = FALSE)library(lubridate)library(readr)library(tidyr)study_day <- function(ref, coll) {  if (is.na(ref) || is.na(coll)) {    return(NA_integer_)  }  delta <- as.integer(coll - ref)  if (delta >= 0L) delta + 1L else delta}dm <- read_csv(  "/app/input/dm.csv",  col_types = cols(.default = col_character()))odm <- read_csv(  "/app/input/odm.csv",  col_types = cols(.default = col_character()))ref_map <- setNames(suppressWarnings(ymd(dm$RFSTDTC)), dm$USUBJID)wide <- odm |>  mutate(visit_key = paste(SubjectKey, StudyEventOID, StudyEventRepeatKey, sep = "|")) |>  select(visit_key, SubjectKey, StudyOID, StudyEventOID, ItemOID, Value) |>  pivot_wider(names_from = ItemOID, values_from = Value, values_fn = first)sv <- wide |>  rowwise() |>  mutate(    dates = list(na.omit(c(IT.VS.VSDTC, IT.LB.LBDTC, IT.EX.EXDTC))),    SVSTDTC = if (length(dates) == 0) NA_character_ else min(dates),    SVENDTC = if (length(dates) == 0) NA_character_ else max(dates)  ) |>  ungroup() |>  filter(!is.na(SVSTDTC)) |>  transmute(    DOMAIN = "SV",    STUDYID = StudyOID,    USUBJID = SubjectKey,    VISIT = IT.TV.VISIT,    VISITNUM = suppressWarnings(as.numeric(IT.TV.VISITNUM)),    VISITDY = suppressWarnings(as.integer(IT.TV.VISITDY)),    SVSTDTC,    SVENDTC,    SVSTDY = vapply(      seq_len(n()),      function(i) study_day(ref_map[[USUBJID[i]]], suppressWarnings(ymd(SVSTDTC[i]))),      integer(1)    ),    SVENDY = vapply(      seq_len(n()),      function(i) study_day(ref_map[[USUBJID[i]]], suppressWarnings(ymd(SVENDTC[i]))),      integer(1)    ),    TAETORD = suppressWarnings(as.integer(IT.TV.TAETORD)),    EPOCH = IT.TV.EPOCH,    SVUPDES = IT.TV.UPDES  ) |>  arrange(USUBJID, SVSTDTC) |>  group_by(USUBJID) |>  mutate(SVSEQ = row_number()) |>  ungroup() |>  arrange(USUBJID, SVSEQ) |>  select(    DOMAIN, STUDYID, USUBJID, SVSEQ, VISIT, VISITNUM, VISITDY, SVSTDTC,    SVENDTC, SVSTDY, SVENDY, TAETORD, EPOCH, SVUPDES  )dir.create("/app/output", showWarnings = FALSE)write_csv(sv, "/app/output/sv.csv", na = "")

solutions/sdtm-sv-subject-visits/result.py

Edit
107 lines
# Reference solution for the yamaa benchmark sdtm-sv-subject-visits (Python track).## Written from the benchmark's full prompt and its inputs alone, as an agent# would write it. Harbor's oracle agent runs it to check that the prompt can# be solved and that the grader scores a correct answer 1.from datetime import datefrom pathlib import Pathimport polars as pldef parse_date(text: str | None) -> date | None:    if text is None or text == "":        return None    try:        return date.fromisoformat(text[:10])    except ValueError:        return Nonedef study_day(ref: date | None, coll: date | None) -> int | None:    if ref is None or coll is None:        return None    delta = (coll - ref).days    return delta + 1 if delta >= 0 else deltadm = pl.read_csv("/app/input/dm.csv", infer_schema=False)odm = pl.read_csv("/app/input/odm.csv", infer_schema=False)ref_map = {row["USUBJID"]: parse_date(row["RFSTDTC"]) for row in dm.to_dicts()}study_map = {row["USUBJID"]: row["STUDYID"] for row in dm.to_dicts()}date_items = {"IT.VS.VSDTC", "IT.LB.LBDTC", "IT.EX.EXDTC"}visits: dict[tuple[str, str, str], dict] = {}for row in odm.to_dicts():    key = (row["SubjectKey"], row["StudyEventOID"], row["StudyEventRepeatKey"])    entry = visits.setdefault(        key,        {            "subject": row["SubjectKey"],            "study": row["StudyOID"],            "tv": {},            "dates": [],        },    )    item = row["ItemOID"]    value = row["Value"]    if item.startswith("IT.TV."):        entry["tv"][item] = value    elif item in date_items and value not in (None, ""):        entry["dates"].append(value)records = []for entry in visits.values():    tv = entry["tv"]    dates = sorted(entry["dates"])    if not dates:        continue    start, end = dates[0], dates[-1]    ref = ref_map.get(entry["subject"])    records.append(        {            "DOMAIN": "SV",            "STUDYID": entry["study"],            "USUBJID": entry["subject"],            "VISIT": tv.get("IT.TV.VISIT"),            "VISITNUM": float(tv["IT.TV.VISITNUM"]) if tv.get("IT.TV.VISITNUM") not in (None, "") else None,            "VISITDY": int(tv["IT.TV.VISITDY"]) if tv.get("IT.TV.VISITDY") not in (None, "") else None,            "SVSTDTC": start,            "SVENDTC": end,            "_start": start,            "SVSTDY": study_day(ref, parse_date(start)),            "SVENDY": study_day(ref, parse_date(end)),            "TAETORD": int(tv["IT.TV.TAETORD"]) if tv.get("IT.TV.TAETORD") not in (None, "") else None,            "EPOCH": tv.get("IT.TV.EPOCH"),            "SVUPDES": tv.get("IT.TV.UPDES"),        }    )sv = (    pl.DataFrame(records)    .sort(["USUBJID", "_start"])    .with_columns(SVSEQ=pl.int_range(1, pl.len() + 1).over("USUBJID"))    .sort(["USUBJID", "SVSEQ"])    .select(        "DOMAIN",        "STUDYID",        "USUBJID",        "SVSEQ",        "VISIT",        "VISITNUM",        "VISITDY",        "SVSTDTC",        "SVENDTC",        "SVSTDY",        "SVENDY",        "TAETORD",        "EPOCH",        "SVUPDES",    ))Path("/app/output").mkdir(exist_ok=True)sv.write_csv("/app/output/sv.csv")

solutions/sdtm-sv-subject-visits/result.sas

Edit
46 lines
/* opensas reference solution for the yamaa benchmark sdtm-sv-subject-visits.   Reads the benchmark inputs and derives the requested output.   Execute with the existing opensas runtime: opensas /app/output/result.sas. */data dm;  length STUDYID USUBJID RFSTDTC $1024;  infile "/app/input/dm.csv" dsd dlm="," firstobs=2 truncover lrecl=32767;  input STUDYID : $char1024. USUBJID : $char1024. RFSTDTC : $char1024.;run;data odm;  length StudyOID MetaDataVersionOID SubjectKey StudyEventOID StudyEventRepeatKey ItemGroupOID ItemGroupRepeatKey ItemOID Value $1024;  infile "/app/input/odm.csv" dsd dlm="," firstobs=2 truncover lrecl=32767;  input StudyOID : $char1024. MetaDataVersionOID : $char1024. SubjectKey : $char1024. StudyEventOID : $char1024. StudyEventRepeatKey : $char1024. ItemGroupOID : $char1024. ItemGroupRepeatKey : $char1024. ItemOID : $char1024. Value : $char1024.;run;proc sort data=odm out=ordered; by StudyOID SubjectKey StudyEventOID StudyEventRepeatKey; run;data visits;  length VISIT VNUM VDAY ORD EPOCH SVUPDES $1024;  retain VISIT VNUM VDAY ORD EPOCH SVUPDES;  set ordered;  by StudyOID SubjectKey StudyEventOID StudyEventRepeatKey;  if first.StudyEventRepeatKey then do;    VISIT=''; VNUM=''; VDAY=''; ORD=''; EPOCH=''; SVUPDES='';  end;    if ItemOID='IT.TV.VISIT' then VISIT=Value;  if ItemOID='IT.TV.VISITNUM' then VNUM=Value;  if ItemOID='IT.TV.VISITDY' then VDAY=Value;  if ItemOID='IT.TV.TAETORD' then ORD=Value;  if ItemOID='IT.TV.EPOCH' then EPOCH=Value;  if ItemOID='IT.TV.UPDES' then SVUPDES=Value;  if last.StudyEventRepeatKey then output;run;proc sql;create table dates as select StudyOID,SubjectKey,StudyEventOID,StudyEventRepeatKey,min(Value) as SVSTDTC,max(Value) as SVENDTC from odm where ItemOID in ('IT.VS.VSDTC','IT.LB.LBDTC','IT.EX.EXDTC') and not missing(Value) group by StudyOID,SubjectKey,StudyEventOID,StudyEventRepeatKey;create table joined as select a.*,b.SVSTDTC,b.SVENDTC,c.RFSTDTC from visits a inner join dates b on a.StudyOID=b.StudyOID and a.SubjectKey=b.SubjectKey and a.StudyEventOID=b.StudyEventOID and a.StudyEventRepeatKey=b.StudyEventRepeatKey left join dm c on a.StudyOID=c.STUDYID and a.SubjectKey=c.USUBJID; quit;data prepared; set joined; length DOMAIN $2 STUDYID USUBJID $1024; DOMAIN='SV'; STUDYID=StudyOID; USUBJID=SubjectKey; VISITNUM=input(VNUM,best32.); VISITDY=input(VDAY,best32.); TAETORD=input(ORD,best32.); SVSTDY=.; SVENDY=.; if not missing(RFSTDTC) then do; SVSTDY=input(SVSTDTC,yymmdd10.)-input(RFSTDTC,yymmdd10.); if SVSTDY>=0 then SVSTDY+1; SVENDY=input(SVENDTC,yymmdd10.)-input(RFSTDTC,yymmdd10.); if SVENDY>=0 then SVENDY+1; end; run;proc sort data=prepared; by STUDYID USUBJID SVSTDTC StudyEventOID StudyEventRepeatKey; run;data result; set prepared; by STUDYID USUBJID; retain SVSEQ UNSCH;if first.USUBJID then do; SVSEQ=0; UNSCH=0; end; SVSEQ+1;if StudyEventOID='UNSCH' then do; UNSCH+1; VISITNUM=99+UNSCH/10; VISITDY=.; TAETORD=.; end; else SVUPDES=''; run;proc sql;  create table final as select DOMAIN, STUDYID, USUBJID, SVSEQ, VISIT, VISITNUM, VISITDY, SVSTDTC, SVENDTC, SVSTDY, SVENDY, TAETORD, EPOCH, SVUPDES from result;quit;proc export data=final outfile="/app/output/sv.csv" dbms=csv replace; run;