SQL - How to combine rows based on unique values

一世执手 提交于 2021-01-28 23:51:52

问题


The table below was created from another table with columns ID,Name,Organ,and Age. The values found in the Organ column were codes which designated both organ and condition.

Using CASE I made a table like this:

--------------------------------------------------------
ID      NAME        Heart   Brain   Lungs   Kidneys AGE
1318    Joe Smith   NULL    NULL    NULL    NULL    50
1318    Joe Smith   NULL    NULL    NULL    NULL    50
1318    Joe Smith   NULL    NULL    NULL    Below   50
1318    Joe Smith   NULL    NULL    NULL    Below   50
1318    Joe Smith   NULL    NULL    Above   NULL    50
1318    Joe Smith   NULL    NULL    Above   NULL    50
1318    Joe Smith   Average NULL    NULL    NULL    50
1318    Joe Smith   Average NULL    NULL    NULL    50
--------------------------------------------------------

I would like to query this table and get the following result:

--------------------------------------------------------
1318    Joe Smith   Average NULL    Above   Below   50   
--------------------------------------------------------

In other words I would like to create one record based on the unique values from each column.


回答1:


Assuming each organ can either have just one value or a null, as shown in the sample data, the max aggregate function should do the trick:

SELECT   id, name, 
         MAX(heart), MAX(brain), MAX(lungs), MAX(kidneys), 
         age
FROM     my_table
GORUP BY id, name, age



回答2:


    select id,name,heart=(select distinct(heart) from organ where id=1318 and heart is not null)
    ,brain= (select distinct(brain) from organ where id=1318 and brain is not null)
    ,lungs=(select distinct(lungs) from organ where id=1318 and lungs is not null)
    ,kidneys = (select distinct(kidneys) from organ where id=1318 and kidneys is not null)
    ,age from organ where id=1318



回答3:


What you want to do here is aggregate your results by ID and NAME. This means that there will only be one row for each unique (ID, NAME) pair. This can be achieved with the GROUP BY keyword.

Now, depending on the Database you are using (MySQL, DB2, ...) this query might look a bit different, but you could try this one:

SELECT 
   ID, NAME, 
   MAX(Heart), MAX(Brain), MAX(Lungs), MAX(Kidneys), MAX(AGE) 
FROM MYTABLE GROUP BY ID, NAME

This will give you the "maximum" value of each column. Like I said, depending on your Database this might not work with string columns, so you could also try COALESCE, which gives you the first NOT NULL value of a list:

SELECT 
   ID, NAME, 
   COALESCE(Heart), COALESCE(Brain), COALESCE(Lungs), COALESCE(Kidneys), COALESCE(AGE) 
FROM MYTABLE GROUP BY ID, NAME


来源:https://stackoverflow.com/questions/27552610/sql-how-to-combine-rows-based-on-unique-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!