本文介紹了分解表以按列進(jìn)行透視(SQL、PYSPARK)的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
我正在使用 AWS Glue 中的 python3.6 環(huán)境在 pyspark 中工作.我有這張桌子:
I'm working in an environment pyspark with python3.6 in AWS Glue. I have this table :
+----+-----+-----+-----+
|year|month|total| loop|
+----+-----+-----+-----+
|2012| 1| 20|loop1|
|2012| 2| 30|loop1|
|2012| 1| 10|loop2|
|2012| 2| 5|loop2|
|2012| 1| 50|loop3|
|2012| 2| 60|loop3|
+----+-----+-----+-----+
我需要得到如下輸出:
year month total_loop1 total_loop2 total_loop3
2012 1 20 10 50
2012 2 30 5 60
我越接近 SQL 代碼:
The closer I have gotten is with the SQL code:
select a.year,a.month, a.total,b.total from test a
left join test b
on a.loop <> b.loop
and a.year = b.year and a.month=b.month
輸出仍然到目前為止:
+----+-----+-----+-----+
|year|month|total|total|
+----+-----+-----+-----+
|2012| 1| 20| 10|
|2012| 1| 20| 50|
|2012| 1| 10| 20|
|2012| 1| 10| 50|
|2012| 1| 50| 20|
|2012| 1| 50| 10|
|2012| 2| 30| 5|
|2012| 2| 30| 60|
|2012| 2| 5| 30|
|2012| 2| 5| 60|
|2012| 2| 60| 30|
|2012| 2| 60| 5|
+----+-----+-----+-----+
我該怎么做?非常感謝
推薦答案
表腳本和示例數(shù)據(jù)
CREATE TABLE [TableName](
[year] [nvarchar](50) NULL,
[month] [int] NULL,
[total] [int] NULL,
[loop] [nvarchar](50) NULL
)
INSERT [TableName] ([year], [month], [total], [loop]) VALUES (N'2012', 1, 20, N'loop1')
INSERT [TableName] ([year], [month], [total], [loop]) VALUES (N'2012', 2, 30, N'loop1')
INSERT [TableName] ([year], [month], [total], [loop]) VALUES (N'2012', 1, 10, N'loop2')
INSERT [TableName] ([year], [month], [total], [loop]) VALUES (N'2012', 2, 5, N'loop2')
INSERT [TableName] ([year], [month], [total], [loop]) VALUES (N'2012', 1, 50, N'loop3')
INSERT [TableName] ([year], [month], [total], [loop]) VALUES (N'2012', 2, 60, N'loop3')
使用樞軸功能...
SELECT *
FROM TableName
PIVOT(Max([total])
FOR [loop] IN ([loop1], [loop2], [loop3]) ) pvt
在線演示:http://www.sqlfiddle.com/#!18/164a4/1/0
如果您正在尋找動(dòng)態(tài)解決方案,那么試試這個(gè)...(動(dòng)態(tài)樞軸)
If you are looking for a dynamic solution, then try this... (Dynamic Pivot)
DECLARE @cols AS NVARCHAR(max) = Stuff((SELECT DISTINCT ',' + Quotename([loop])
FROM TableName
FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, '');
DECLARE @query AS NVARCHAR(max) = 'SELECT *
FROM TableName
PIVOT(Max([total])
FOR [loop] IN ('+ @cols +') ) pvt';
EXECUTE(@query)
在線演示:http://www.sqlfiddle.com/#!18/164a4/3/0
輸出
+------+-------+-------+-------+-------+
| year | month | loop1 | loop2 | loop3 |
+------+-------+-------+-------+-------+
| 2012 | 1 | 20 | 10 | 50 |
| 2012 | 2 | 30 | 5 | 60 |
+------+-------+-------+-------+-------+
這篇關(guān)于分解表以按列進(jìn)行透視(SQL、PYSPARK)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!