简体   繁体   English

转置 SQL 中的一列数据

[英]Transposing a column of data in SQL

In SQL my data output is在 SQL 我的数据 output 是

Agreement ID协议编号 ProductStatus产品状态
125 125 A一个
125 125 C C
125 125 N ñ

I want to see this instead as我想看到这个而不是

Agreement ID协议编号 ProductStatus产品状态
125 125 A,C, N A,C, N

OR或者

Agreement ID协议编号 ProductStatus1产品状态1 ProductStatus2产品状态2 ProductStatus3产品状态3
125 125 A一个 C C N ñ

I've tried a few simple pivots, but the values a, c & n CAN be different and random values each time.我尝试了一些简单的枢轴,但值 a、c & n 每次都可以是不同的随机值。 Can anyone help?任何人都可以帮忙吗?

You can use a group_concat function.您可以使用 group_concat function。 Your query will be something like this您的查询将是这样的

SELECT agreement_id, group_concat(Product_Status)
FrOM mytable
group by agreement_id

This is for MySQL, for other databases you can search for group_concat alternative function for that particular database.这适用于 MySQL,对于其他数据库,您可以为该特定数据库搜索 group_concat 替代 function。 Seems like you are new to database.好像您是数据库新手。 You can use this reference to learn more.您可以使用此参考来了解更多信息。 https://www.mysqltutorial.org/basic-mysql-tutorial.aspx https://www.mysqltutorial.org/basic-mysql-tutorial.aspx

If you can get three values in different columns using conditional aggregation:如果您可以使用条件聚合在不同的列中获取三个值:

select agreementid,
       max(case when seqnum = 1 then ProductStatus end) as ProductStatus_1,
       max(case when seqnum = 2 then ProductStatus end) as ProductStatus_2,
       max(case when seqnum = 3 then ProductStatus end) as ProductStatus_3
from (select t.*,
             row_number() over (partition by agreementid order by agreementid) as seqnum
      from t
     ) t
group by agreementid;

The SQL standard for creating a list is:用于创建列表的 SQL 标准是:

select agreementid,
       list_agg(ProductStatus, ',') within group (order by productstatus) as productstatuses
from t
group by agreementid;

Many databases have different names for this function.许多数据库对此 function 有不同的名称。

In both of these cases, the ordering of the columns or elements of the list are indeterminate.在这两种情况下,列表的列或元素的顺序是不确定的。 SQL table represent unordered sets (well, technically multisets) so there is no ordering unless a column specifies the ordering. SQL 表表示无序集(嗯,技术上是多集),因此除非列指定排序,否则没有排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM