SQL查询-将数据复制到一个字段

时间:2020-04-25 06:20:37

标签: sql sql-server

我有一个SQL数据库,正在编写查询:

public Mono<CardCollection> findAllCards(MultiValueMap<String, String> queryParams) {
  return tokenRepository.requestToken().flatMap(token -> {
      return cardRepository.findAllCards(token.getAccessToken(), queryParams);
  });
}

第一栏中是:consignment_id [这是从寄售表中得到的]]最后一栏中是:senders_reference [这是从UserReferences表中得到的]

现在-我的问题是-当我运行查询以提取特定日期的所有货物时-当数据库中存在多个发件人引用时,它将显示多行(具有重复的consignment_id)。

>

如果发件人参考号为1,则只有1行。

这很有道理-因为在数据库的前端,用户可以输入1个或多个发件人引用。

现在-我想对查询结果数据进行查询,以对所有托运货物仅显示1行,如果有多个发件人参考编号,则将它们放在一个字段中,并用逗号分隔。 / p>

这在查询阶段是否可行?

或者,如果不是-导出后,是否可以开发一个bat文件来做同样的事情?

仅供参考-这就是我的意思-这是我目前所得到的结果: data i'm getting at the moment 这就是我需要的:

what i need

2 个答案:

答案 0 :(得分:1)

您似乎想使用STRING_AGG函数。

这个答案很好地涵盖了它 ListAGG in SQLSERVER

答案 1 :(得分:1)

您可以在for xml的帮助下使用较旧的样式:

select t.consignment_id,
       stuff((select ', ' +convert(varchar(255), t1.sender_reference)
              from table t1 
              where t1.consignment_id = t.consignment_id
              for xml path('')
             ), 1, 1, ''
            ) as senders_reference
from (select distinct consignment_id from table t) t;

编辑:您可以使用CTE

with cte as (
     <your query>
)
select t.consignment_id,
       stuff((select ', ' +convert(varchar(255), t1.sender_reference)
              from cte t1 
              where t1.consignment_id = t.consignment_id
              for xml path('')
             ), 1, 1, ''
            ) as senders_reference
from (select distinct consignment_id from cte t) t;
相关问题