透视 SQL 语句
我有一个像这样的表(当然还有更多的值,但你明白了):
ID Name
--- ----
1 A
1 B
2 C
3 D
4 A
4 D
4 E
4 F
4 G
4 H
我想编写一个输出这个的查询,因为一个 ID 不能有超过 6 个名称。
ID Name1 Name2 Name3 Name4 Name5 Name6
--- ------ ------ ------ ------ ------ -----
1 A B
2 C
3 D
4 A D E F G H
I have a table like this (of course there are many more values but you get the idea):
ID Name
--- ----
1 A
1 B
2 C
3 D
4 A
4 D
4 E
4 F
4 G
4 H
I want to write a query that would output this, given that an ID cannot have more than 6 names.
ID Name1 Name2 Name3 Name4 Name5 Name6
--- ------ ------ ------ ------ ------ -----
1 A B
2 C
3 D
4 A D E F G H
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试:
非 CTE 等效项:
参考:
Try:
Non CTE equivalent:
Reference:
我创建了一个名为pivot_query 的存储过程,以使PIVOT 语句更加灵活。它的来源是此处。还有一个如何使用它的示例。
借用下面 OMG Ponies 的一段代码,并稍微更改一下查询,
那么对pivot_query的调用将如下所示:
现在的结果如下所示:
但不完全确定您要显示的内容。 :-)
虽然这本质上不会将输出限制为 6 个名称列,但它会继续上升,除非您添加一个 where 子句来专门排除 6 以上的排名。
I created a stored procedure named pivot_query to make the PIVOT statement a little more flexible. The source for it is here. There is also an example of how to use it.
Borrowing a piece of code from OMG Ponies below, and changing the query a bit,
then the call to pivot_query would look like this:
and the results now look like this:
Not exactly sure what you're trying to show, though. :-)
This will not intrinsically limit the output to the 6 name columns though, it will keep going up unless you add a where clause to specifically exclude ranks above 6.