连接同一列

时间:2017-02-28 21:23:46

标签: sql sql-server

我有一行SQL导致2行1个单元格返回:

SELECT ATTR_VAL FROM [NDC_ATTR] where item_id = 185836 and field_id IN (144,225) 

结果:

1 H400

2 TESTTEXT

我正在尝试将它们连接在一起,因此它们看起来像这样' TESTTEXT [H400]':

select concat (
        [NDC_ATTR],
        ' ',
        [NDC_ATTR]
        ) as newColumn
where item_id = 185836
    and field_id in (144, 225)

但是,我收到一堆错误,说列名是错误的。

我认为这是因为两个细胞来自同一列。

我做错了什么以及如何解决?

1 个答案:

答案 0 :(得分:3)

select newColumn = stuff(
  (
  select '' +[ATTR_VAL]
    from [NDC_ATTR]
    where item_id = 185836
      and field_id in (144, 225)
    order by 1 desc
  for xml path (''), type).value('.','varchar(max)')
  ,1,0,'')

或更多项目:

select 
    t.item_id
  , newColumn = stuff(
  (
  select '' +[ATTR_VAL]
    from [NDC_ATTR] as i
    where i.item_id = t.item_id
      and i.field_id in (144, 225)
    order by 1 desc
  for xml path (''), type).value('.','varchar(max)')
  ,1,0,'')
  from [NDC_ATTR] as t
  where t.item_id in (...)
  group by t.item_id

可选:添加一个分隔符:(注意0更改为';'的第3个参数的分隔符stuff的长度

select 
    t.item_id
  , newColumn = stuff(
  (
  select ';' +[ATTR_VAL]
    from [NDC_ATTR] as i
    where i.item_id = t.item_id
      and i.field_id in (144, 225)
    order by 1 desc
  for xml path (''), type).value('.','varchar(max)')
  ,1,1,'')
  from [NDC_ATTR] as t
  where t.item_id in (...)
  group by t.item_id