[英]PL/SQL: Join statements in for loop
I am a beginner in PL/SQL.我是 PL/SQL 的初学者。
I am trying to loop through every months in a specific dataframe, select a couple of attributes for each user and append it (join) into a table where each row represents one user.我试图在特定数据框中每个月循环一次,为每个用户选择几个属性并将其附加(加入)到一个表中,其中每一行代表一个用户。 I am very open for alternative (possibly faster), completely different sollutions.我对替代(可能更快),完全不同的解决方案非常开放。
BEGIN
ResultTable = ???
FOR k IN 1..24 LOOP
SELECT * FROM(
SELECT a.Userid, a.size as ('size, time=' || to_char(k)), a.weight as ('weight, time=' || to_char(k))
FROM Original a
INNER JOIN ResultTable b
ON a.Userid= b.Userid
) ResultTable
END LOOP;
END;
For example:例如:
+--------+------+------+--------+----+
| ID | time | size | weight | … |
+--------+------+------+--------+----+
| 1 | 1 | 4 | 5 | .. |
| 1 | 2 | 6 | 11 | .. |
| 1 | … | .. | .. | .. |
| 1 | 24 | 8 | 3 | .. |
| 2 | 1 | 4 | 5 | .. |
| 2 | 2 | 8 | 11 | .. |
| 2 | … | .. | .. | .. |
| 2 | 24 | 18 | 5 | .. |
| … | … | … | … | … |
| 278000 | 1 | 8 | 6 | .. |
| 278000 | 2 | 16 | 11 | .. |
| 278000 | … | .. | .. | .. |
| 278000 | 24 | 8 | 3 | .. |
+--------+------+------+--------+----+
+--------+--------+---------+-------+---------+---+--------+----------+
| ID | size1 | weight1 | size2 | weight2 | … | size24 | weight24 |
+--------+--------+---------+-------+---------+---+--------+----------+
| 1 | 4 | 5 | 6 | 11 | … | 8 | 3 |
| 2 | 4 | 5 | 8 | 11 | … | 18 | 5 |
| … | … | … | … | … | … | … | … |
| 278000 | 8 | 6 | 16 | 11 | … | 8 | 3 |
+--------+--------+---------+-------+---------+---+--------+----------+
I have edited my question to make it more readable.我编辑了我的问题以使其更具可读性。
You can use PIVOT
as following:您可以使用PIVOT
如下:
SELECT * FROM
(
SELECT ID, TIME, SIZE, WEIGHT FROM YOUR_TABLE
)
PIVOT
(
MAX(SIZE) AS SIZE, MAX(WEIGHT) AS WEIGHT
FOR TIME IN (1,2,3,...24)
)
Cheers!!干杯!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.