【问题标题】:SQL - How to combine rows based on unique valuesSQL - 如何根据唯一值组合行
【发布时间】:2014-12-18 17:43:56
【问题描述】:

下表是从另一个包含 ID、名称、器官和年龄列的表创建的。 器官列中的值是指定器官和条件的代码。

使用 CASE 我做了一个这样的表:

--------------------------------------------------------
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
--------------------------------------------------------

我想查询这张表,得到如下结果:

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

换句话说,我想根据每个记录的唯一值创建一个记录 列。

【问题讨论】:

  • 这是什么数据库?
  • 嗯...我想说你可能想回到原来的表并从它们做一些事情,而不是基于这个中间步骤来查询 - 这似乎很笨拙。
  • 适用于 MS sql-server

标签: sql sql-server string select unique


【解决方案1】:

假设每个器官只有一个值或null,如示例数据所示,max 聚合函数应该可以解决问题:

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

【讨论】:

  • 成功了!我不知道字符串上的 max() 。非常感谢!
【解决方案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】:

    您在此处要做的是按 ID 和 NAME 汇总您的结果。这意味着每个唯一的 (ID, NAME) 对只有一行。这可以通过GROUP BY 关键字来实现。

    现在,根据您使用的数据库(MySQL、DB2、...),此查询可能看起来有些不同,但您可以试试这个:

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

    这将为您提供每列的“最大值”。就像我说的,根据您的数据库,这可能不适用于字符串列,因此您也可以尝试COALESCE,它会为您提供列表的第一个 NOT NULL 值:

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

    【讨论】:

    • 上面的海报先到了,但感谢您的帮助!我对合并一无所知。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多