简体   繁体   English

如何计算来自同一表的多个列的值

[英]How to count values from multiples columns of the same table

I am trying to construct a single SQL statement that returns unique, non-null values from multiple columns all located in the same table. 我正在尝试构造一个SQL语句,该语句从位于同一表中的多个列返回唯一的非空值。

I tried making this SQL statement by using "sum" and "case" like said in another stackOverflow topic but it didn't work. 我尝试通过使用“ sum”和“ case”来制作此SQL语句,如另一个stackOverflow主题中所述,但是它不起作用。

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

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. 无论如何,在这种情况下,您需要分别获取每个SYMPTOM_X列的结果,并使用UNION对其进行组合。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM