1+ /*
2+ Created by Kollil in Dec 2025
3+ Tkt # 13461
4+ Added two filters to the Demographics dataset:
5+ 1. Filter out any animal with the following SNOMED Codes:
6+ Begin active weight management regimen (P-YY961)
7+ However, we would need to include animals that have this additional SNOMED Code if it's entered AFTER the one above
8+ Release from active weight management regimen (P-YY960)
9+ 2. Remove Shelters, Corral and Hospital locations from the lists
10+ */
11+
12+ SELECT DISTINCT
13+ l .lsid ,
14+ l .Id ,
15+
16+ l .date AS LatestWeightDate,
17+ l .weight AS LatestWeight,
18+
19+ p .date , -- AS PrevWeightDate
20+ p .weight , -- AS PrevWeight
21+
22+ timestampdiff(' SQL_TSI_DAY' , p .date , l .date ) AS IntervalInDays,
23+ age_in_months(p .date , l .date ) AS IntervalInMonths,
24+
25+ CASE
26+ WHEN p .weight IS NOT NULL AND p .weight > 0 THEN
27+ ROUND(((l .weight - p .weight ) * 100 / p .weight ), 1 )
28+ ELSE NULL
29+ END AS PctChange,
30+
31+ CASE
32+ WHEN p .weight IS NOT NULL AND p .weight > 0 THEN
33+ ABS(ROUND(((l .weight - p .weight ) * 100 / p .weight ), 1 ))
34+ ELSE NULL
35+ END AS AbsPctChange,
36+
37+ l .qcstate AS LatestQcState,
38+ p .qcstate AS PrevQcState
39+
40+ FROM
41+ (SELECT Id, MAX (date ) AS LatestDate
42+ FROM study .weight
43+ GROUP BY Id) lw
44+
45+ JOIN study .weight l
46+ ON l .Id = lw .Id
47+ AND l .date = lw .LatestDate
48+
49+ LEFT JOIN study .weight p
50+ ON p .Id = lw .Id
51+ AND p .date = (
52+ SELECT MAX (w2 .date )
53+ FROM study .weight w2
54+ WHERE w2 .Id = lw .Id
55+ AND w2 .date <= timestampadd(' SQL_TSI_DAY' , - 30 , lw .LatestDate )
56+ AND w2 .date >= timestampadd(' SQL_TSI_DAY' , - 100 , lw .LatestDate )
57+ )
58+
59+ WHERE l .Id .curlocation .area NOT IN (' Shelters' , ' Corral' , ' Hospital' , ' Catch Area' )-- Exclude animals from these locations
60+ AND NOT (-- Exclude females under 5yrs, males under 7yrs
61+ (l .Id .demographics .gender .code = ' f' AND l .Id .age .ageInYears < 5 )
62+ OR (l .Id .demographics .gender .code = ' m' AND l .Id .age .ageInYears < 7 )
63+ )
64+ AND l .qcstate .publicdata = true
65+ AND NOT EXISTS (
66+ -- -- Find animals whose latest 'Weight MMA BEGIN' has no later 'Weight MMA RELEASE'
67+ SELECT 1
68+ FROM study .WeightMMA b
69+ WHERE b .Id = l .Id
70+ AND b .code = ' P-YY961'
71+ AND b .date = (
72+ SELECT MAX (b2 .date )
73+ FROM study .WeightMMA b2
74+ WHERE b2 .Id = l .Id
75+ AND b2 .code = ' P-YY961'
76+ )
77+ AND NOT EXISTS (
78+ SELECT 1
79+ FROM study .WeightMMA r
80+ WHERE r .Id = l .Id
81+ AND r .code = ' P-YY960'
82+ AND r .date > b .date
83+ )
84+ )
0 commit comments