My goal is to collect data that contains "POSITIVE" result and code sets that must contain U071 or other codes that may be paired with U071 (as a code set). I was trying to group it by ID and CODE U071 only but realized it would only collect ID with U071 only (and not its other codes from each code set). I just need to group the ID with its code set and count it as 1 row. I know my code below is not correct, but what is the best way to group it by PTID with their code set? I hope my question is clear; if not, please feel free to comment below.
Table 1:
| ID | TEST_RESULT | DATE | CODE |
|---|---|---|---|
| 1 | POSITIVE | 12-09-2020 | U071 |
| 1 | POSITIVE | 12-09-2020 | T34 |
| 2 | POSITIVE | 11-09-2020 | U071 |
| 3 | POSITIVE | 01-08-2020 | U071 |
| 3 | POSITIVE | 01-08-2020 | N99 |
| 4 | POSITIVE | 08-11-2020 | W39 |
Problem:
It will exclude ID 1 code {T34} and ID3 with {N99} as one separate set each, instead of recognizing it as ID 1 {T34, U071} and ID 3 {U071, N99} as 1 set each. In other words, ID 1 with code set {T34, U071} => need to count it as 1 row in table2.
Desired Goal for Table 2:
| ID | TEST_RESULT | DATE | CODE |
|---|---|---|---|
| 1 | POSITIVE | 12-09-2020 | T34 |
| 2 | POSITIVE | 11-09-2020 | U071 |
| 3 | POSITIVE | 01-08-2020 | U071 |
Note: For ID 1, it does not matter whether CODE shows T34 or U071. The same applies for ID 3. I just need to group the ID with its code set and count it.
My code:
CREATE TABLE table2 AS
SELECT ID, TEST_RESULT, DATE, CODE
FROM table1
WHERE TEST_RESULT='POSITIVE' AND CODE = '%U071%'
group by ID
ORDER BY ID ASC;
>Solution :
select ID
,TEST_RESULT
,max(DATE) as 'Date'
,max(CODE) as Code
,count(*) as 'Count'
from
(
select *
,count(case when CODE='U071' and TEST_RESULT = 'POSITIVE' then 1 end) over (partition by ID,TEST_RESULT) as cnt
from t
) t
group by ID, TEST_RESULT
having cnt > 0 and TEST_RESULT = 'POSITIVE'
| ID | TEST_RESULT | Date | Code | Count |
|---|---|---|---|---|
| 1 | POSITIVE | 12-09-2020 | U071 | 2 |
| 2 | POSITIVE | 11-09-2020 | U071 | 1 |
| 3 | POSITIVE | 01-08-2020 | U071 | 2 |