将列按行号转置为行,不包含任何“id”或键列。

huangapple go评论69阅读模式
英文:

Transpose column to row without any 'id' or key column based on row number

问题

抱歉,您提供的内容已经是英文的数据库查询问题,无需进一步翻译。如果您需要关于这个查询问题的帮助或解决方案,请随时向我提问。

英文:

Hi I have table like this

name cat_type
coco Dom
coky Anggora
chee Turk
eena Persian
onaa Dom
haina Turk
haani Dom

I want to try to transform to this

Dom Anggora Turk Persian
coco coky chee eena
onaa null haina null
haani null null null

I have tried the following approach:

SELECT *
FROM my_table
PIVOT( STRING_AGG(name) FOR cat_type IN ('Dom','Anggora','Turk','Persian'))   

But I didn't get what I want, as I got result like the following:

Dom Anggora Turk Persian
coco,onaa,haani coky chee,haina eena

Is there something wrong in my query?

Thank you in advance!

答案1

得分: 0

这个问题看起来像是经典的数据透视表的一个略微变种。你所遗漏的是你正在分组的列,而在你的情况下,它是行号。

WITH cte AS(
    SELECT *, ROW_NUMBER() OVER(PARTITION BY cat_type ORDER BY name) AS rn
    FROM my_table
)
SELECT * 
FROM cte
PIVOT (STRING_AGG(name) FOR cat_type IN ('Dom','Anggora','Turk','Persian'))
英文:

This problem looks like a slightly variation of classical pivot. What you're missing is the column you're grouping by, which in your case is the row number.

WITH cte AS(
    SELECT *, ROW_NUMBER() OVER(PARTITION BY cat_type ORDER BY name) AS rn
    FROM my_table
)
SELECT *, 
FROM cte
PIVOT (STRING_AGG(name) FOR cat_type IN ('Dom','Anggora','Turk','Persian'))

huangapple
  • 本文由 发表于 2023年6月6日 17:29:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76413240.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定