Easiest way to eliminate NULLs in SELECT DISTINCT?

前端 未结 8 538
我寻月下人不归
我寻月下人不归 2020-12-10 01:28

I am working on a query that is fairly similar the following:

CREATE TABLE #test (a char(1), b char(1))

INSERT INTO #test(a,b) VALUES 
(\'A\',NULL),
(\'A\',         


        
相关标签:
8条回答
  • 2020-12-10 01:40
    ;WITH CTE
        AS
        (
        SELECT DISTINCT * FROM #test
        )
        SELECT a,b
        FROM CTE        
        ORDER BY CASE WHEN b IS NULL THEN 9999 ELSE b END ; 
    
    0 讨论(0)
  • 2020-12-10 01:42

    I'll just put here a mix of two answers that solved my issue, because my View was more complex

        --IdCompe int,
        --Nome varchar(30),
        --IdVanBanco int,
        --IdVan int
        --FlagAtivo bit,
        --FlagPrincipal bit
    
        select IdCompe
               , Nome
               , max(IdVanBanco)
               , max(IdVan)
               , CAST(MAX(CAST(FlagAtivo as INT)) AS BIT) FlagAtivo
               , CAST(MAX(CAST(FlagPrincipal as INT)) AS BIT) FlagPrincipal
        from VwVanBanco
               where IdVan = {IdVan} or IdVan is null
               group by IdCompe, Nome order by IdCompe asc
    

    Thanks to mosty mostacho and kenwarner

    0 讨论(0)
  • 2020-12-10 01:43

    Well, I don't particularly like this solution, but it seems the most appropriate to me. Note that your description of what you want sounds exactly like what you get with a LEFT JOIN, so:

    SELECT DISTINCT a.a, b.b
    FROM #test a
        LEFT JOIN #test b ON a.a = b.a
            AND b.b IS NOT NULL
    
    0 讨论(0)
  • 2020-12-10 01:45
    SELECT a,b FROM #test t where b is not null
    union
    SELECT a,b FROM #test t where b is null
    and not exists(select 1 from #test where a=t.a and b is not null)
    

    Result:

    a    b
    ---- ----
    A    B
    B    NULL
    
    0 讨论(0)
  • 2020-12-10 01:49

    This is a really weird requirement. I wonder how you need it.

    SELECT DISTINCT a, b
    FROM   test t
    WHERE  NOT ( b IS  NULL
              AND EXISTS 
                  ( SELECT * 
                    FROM test ta 
                    WHERE ta.a = t.a 
                      AND ta.b IS NOT NULL
                   ) 
                 )
      AND  NOT ( a IS  NULL
              AND EXISTS 
                  ( SELECT * 
                    FROM test tb 
                    WHERE tb.b = t.b 
                      AND tb.a IS NOT NULL
                   ) 
                 )
    
    0 讨论(0)
  • 2020-12-10 01:52
    SELECT DISTINCT t.a, t.b
    FROM   #test t
    WHERE  b IS NOT NULL
    OR     NOT EXISTS (SELECT 1 FROM #test u WHERE t.a = u.a AND u.b IS NOT NULL)
    ORDER BY t.a, t.b
    
    0 讨论(0)
提交回复
热议问题