【问题标题】:How to take not values from column of different rows in SQL Server?如何从 SQL Server 中不同行的列中取值?
【发布时间】:2017-05-30 23:23:50
【问题描述】:

谁能帮我解决以下 SQL 要求:

具有如下数据的表:

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

预期结果应该是:

Identifier  brand   brand1  sub_brand
13          ABC     DEF     DEF

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

【问题讨论】:

  • 1) 请不要使用图片来显示您的数据,我不会难为您只是将其粘贴并格式化,阅读this to understand why 2) 请不要标记数据库你不使用,只标记你实际使用的那个,无论如何你都会得到需要的关注。
  • 你可以使用 max() 和 group by 来获取数据
  • 谢谢!...@LudvigRydahl...第一次在论坛上发帖...下次也会这样做。
  • max() of column 为我工作...谢谢!。 @krishnpatel

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


【解决方案1】:

只要您关心的每一列中只有一个值,那么 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

【讨论】:

    【解决方案2】:

    试试这个,

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

    【讨论】:

      【解决方案3】:
      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
      

      【讨论】:

      • 在我的本地测试过,你可以试试。
      【解决方案4】:

      您可以使用以下代码。

      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
      

      【讨论】:

      • 我建议你测试一下。它将返回零行。
      • 这不会。我已更新查询以获得更精确的解决方案。
      • 啊,我看到您使用的样本数据与 OP 完全相同(不幸的是,这是一个非常糟糕的例子)。 brand1sub_brand 不太可能总是相同的。在这种情况下,a.brand1 = b.sub_brand 会适得其反。 PS:根据问题文本,您应该包括a.brand = b.brand
      • 如果您使用适当的子查询代替#Temp a#Temp b,您的答案是可以修复的
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-08
      • 2020-09-21
      相关资源
      最近更新 更多