我将如何在SQL中执行此操作?我有一个表,该表有两列,其中包含需要单独行的数据。一个示例可能在这里效果最好。
这是我表的当前结构:
╔═══════════╦═════════╦═══════╦════════╗
║ CustID ║ Title ║ Plays ║ Shares ║
╠═══════════╬═════════╬═══════╬════════╣
║ Sony ║ Movie 1 ║ 123 ║ 224 ║
║ Sony ║ Movie 2 ║ 344 ║ 766 ║
║ Universal ║ Movie 3 ║ 334 ║ 866 ║
╚═══════════╩═════════╩═══════╩════════╝
我需要在我的select语句中将'plays'和'shares'事件分成不同的行,如下所示:
╔═══════════╦═════════╦════════╦═══════╗
║ CustID ║ Title ║ Events ║ Type ║
╠═══════════╬═════════╬════════╬═══════╣
║ Sony ║ Movie 1 ║ 123 ║ play ║
║ Sony ║ Movie 1 ║ 224 ║ share ║
║ Sony ║ Movie 2 ║ 334 ║ play ║
║ Sony ║ Movie 2 ║ 766 ║ share ║
║ Universal ║ Movie 3 ║ 334 ║ play ║
║ Universal ║ Movie 3 ║ 866 ║ share ║
╚═══════════╩═════════╩════════╩═══════╝
我本质上是在执行SQL数据透视,但是我没有采取多行并将其透视为单个的方法,而是尝试采用另一种方法。有什么好方法吗?我使用的是Postgres9.x。
一种适用于任何数据库(包括Postgres)的方法是使用一系列联合取消数据透视:
SELECT CustID, Title, Plays AS Events, 'play' AS "Type" FROM yourTable
UNION ALL
SELECT CustID, Title, Shares, 'share' FROM yourTable
ORDER BY CustID, Title, Events;
您可以使用交叉联接进行取消透视:
select t.cust_id, t.title, x.event, x.type
from test t
cross join lateral (values (plays, 'plays'), (shares, 'shares')) as x(event, type)
order by t.cust_id, t.title;