Reputation: 1
I am trying to construct a single SQL statement that returns unique, non-null values from multiple columns all located in the same table.
I tried making this SQL statement by using "sum" and "case" like said in another stackOverflow topic but it didn't work.
And I also tried this:
Select count(distinct SYMPTOM_I, SYMPTOM_II, SYMPTOM_III, SYMPTOM_IV)
from DIAGNOSTIC_MEDVIR;
Create table DIAGNOSTIC_MEDVIR(
NIP varchar(32) not null,
DIAGNOSTIC_TIME int not null,
DAY_TIME varchar(32) not null,
SEX varchar(8) not null,
AGE int not null,
SYMPTOM_I varchar(64) not null,
SYMPTOM_II varchar(64),
SYMPTOM_III varchar(64),
SYMPTOM_IV varchar(64),
PATHOLOGY_I varchar(64) not null,
PATHOLOGY_II varchar(64),
PATHOLOGY_III varchar(64),
Constraint NIP_PK primary key(NIP),
Constraint CK_SEX check (SEX='Male' or SEX='Female'),
Constraint CK_DAYTIME(DAY_TIME='Morning' or DAY_TIME='Evening' or
DAY_TIME='Night')
);
Let's say I have into this table:
Insert into DIAGNOSTIC_MEDVIR
values ('195889419', 60, 'Morning', 'Male', 68, 'fever',
'sore throat', 'headache', , 'throat infection', , );
Insert into DIAGNOSTIC_MEDVIR
values ('195889420', 67, 'Morning', 'Female', 38, 'fever',
'headache', , , 'cold', , );
I would like to have:
fever: 2
sore throat: 1
headache: 1
Upvotes: 0
Views: 31
Reputation: 164204
This design is problematic and the proof is the solution itself.
What if you decide to add another column with a 5th symptom?
You would have to change everything, all the queries that return info such as this question.
Anyway in this case you need to get the results for each SYMPTOM_X column separately and use UNION to combine them. Then group to get the total results:
select t.symptom, count(*) counter from (
select SYMPTOM_I symptom from DIAGNOSTIC_MEDVIR
union all
select SYMPTOM_II from DIAGNOSTIC_MEDVIR
union all
select SYMPTOM_III from DIAGNOSTIC_MEDVIR
union all
select SYMPTOM_IV from DIAGNOSTIC_MEDVIR
) t
where t.symptom is not null
group by t.symptom
See the demo.
Results:
> symptom | counter
> :---------- | ------:
> fever | 2
> headache | 2
> sore throat | 1
Upvotes: 1