如何从SQL Server中的不同行的列中取不出值?

时间:2017-01-16 07:01:55

标签: mysql sql sql-server sql-server-2008 tsql

任何人都可以通过SQL帮助我解决以下问题:

表格数据如下:

Identifier  brand   brand1  sub_brand
13          ABC     DEF     NULL
13          ABC     NULL    DEF

预期结果应为:

Identifier  brand   brand1  sub_brand
13          ABC     DEF     DEF

前两列将始终包含相同的值,但其他列仅包含一行数据。我需要一些通用的SQL,因为实际上我有更多的列。

4 个答案:

答案 0 :(得分:2)

只要您关注的每列中只有一个值,那么max和group by应该按照您的意愿行事。如果你有多个,那我就误解了这个问题。

按前两列分组,选择每个列的最大值,如下所示

select ID, brand, MAX(brand1), MAX(subbrand)

from
(
select 13 as ID, 'ABC' as brand, 'DEF' as brand1, NULL as subbrand
union all select 13 as ID, 'ABC' as brand, NULL as brand1, 'DEF' as subbrand
) as testdata

group by ID, brand

答案 1 :(得分:0)

试试这个,

SELECT  Identifier ,
        MAX(Brand) [Brand] ,
        MAX(Brand1) [Brand1] ,
        MAX(Sub_Brand) [Sub Brand]
FROM    Brands
GROUP BY Identifier

答案 2 :(得分:0)

select ( Identifier)  , max (brand ) as brand,max (brand1) as brand1 ,
 case  when max(sub_brand )is null  then max (brand1 )end as sub_brand
  from test  
where  brand1 is not null
   group by Identifier,sub_brand

答案 3 :(得分:-1)

您可以使用以下代码。

CREATE TABLE #Temp
(
    Identifier INT,  
    brand          varchar(20),
    brand1         varchar(20),
    sub_brand     varchar(20)
)

INSERT INTO #Temp
SELECT 
    13,'ABC','DEF',NULL UNION 
SELECT 
    13,'ABC',NULL,'DEF'

SELECT 
        a.Identifier AS Identifier,
        a.Brand AS Brand,
        a.brand1 AS brand1,
    b.sub_brand AS sub_brand
From
    #Temp a
CROSS apply
    #Temp b
WHERE 
    a.Identifier = b.Identifier
AND
    a.brand1 = b.sub_brand