【问题标题】:Records dupped on Nulls - SQL Server在 Null 上重复的记录 - SQL Server
【发布时间】:2016-01-19 02:57:00
【问题描述】:
SELECT 
    a.Name, a.Eats, a.Drinks
FROM 
    xd_animals_test a

结果

Name        Eats    Drinks
Elephant    NULL    Y
Elephant    Y       NULL

获得一个结果的最佳方法是什么? 前

Name        Eats  Drinks
Elephant    Y     Y

这是我的尝试,我不确定它是否是最干净的方式。还有另一种更有效的方法吗?

SELECT
    Names.Name, Eats, Drinks 
FROM
    (SELECT DISTINCT 
         Name 
     FROM
         xd_animals_test) names 
LEFT JOIN 
    (SELECT 
         MAX(name) AS Name, MAX(eats) AS Eats, MAX(drinks) AS Drinks 
     FROM 
         xd_animals_test) eatdrink ON names.Name = EatDrink.Name

【问题讨论】:

    标签: sql sql-server null duplicates


    【解决方案1】:

    您可以在示例中使用聚合:

    SELECT a.Name, max(a.Eats) as eats, max(a.Drinks) as drinks
    FROM xd_animals_test a
    GROUP BY a.Name;
    

    这假设每个name 最多有两行,如问题中的示例所示。

    【讨论】:

      【解决方案2】:

      Select name,
          Case if exists(select * from table 
                         where name = a.name 
                             and Eats ='Y")
              then 'Y' end Eats,
          Case if exists(select * from table 
                         where name = a.name 
                             and Drinks ='Y")
              then 'Y' end Drinks ,
      From table a
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-05-18
        • 1970-01-01
        • 1970-01-01
        • 2011-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多