聚集和旋轉,我想實現旋轉火花星火斯卡拉 - 基於時間段
截至目前,我使用sqlContext和SQL應用內全部改造類似於SQL Server。 我想知道我是否可以直接從sql server中獲取數據並使用spark實現數據透視功能。
下面是什麼,我想achieve- 的SQL Server查詢如下─
create table #temp(ID Int, MonthPrior int, Amount float);
insert into #temp values (100,1,10),(100,2,20),(100,3,30),(100,4,10),(100,5,20),(100,6,60),(200,1,10),(200,2,20),(200,3,30),(300,4,10),(300,5,20),(300,6,60);
select * from #temp;
的例子| ID | MonthPrior | 金額 |
| ------- | ---------- | ------ |
| 100 | 1 | 10 |
| 100 | 2 | 20 |
| 100 | 3 | 30 |
| 100 | 4 | 10 |
| 100 | 5 | 20 |
| 100 | 6 | 60 |
| 200 | 1 | 10 |
| 200 | 2 | 20 |
| 200 | 3 | 30 |
| 300 | 4 | 10 |
| 300 | 5 | 20 |
| 300 | 6 | 60 |
Select ID,coalesce([1],0) as Amount1Mth, coalesce([1],0)+coalesce([2],0)+coalesce([3],0) as Amount1to3Mth, coalesce([1],0)+coalesce([2],0)+coalesce([3],0)+coalesce([4],0)+coalesce([5],0)+coalesce([6],0) as Amount_AllMonths from (select * from #temp) A pivot (sum(Amount) for MonthPrior in ([1],[2],[3],[4],[5],[6])) as Pvt
| ID | 金額1月 | Amount1to3thth | Amount_AllMonths |
| ------- | ------- | ------- | --- |
| 100 | 10 | 60 | 150 |
| 200 | 10 | 60 | 60 |
| 300 | 0 | 0 | 90 |
謝謝@LeoC 我會分析一下這個方法。似乎工作 –
很高興它有幫助。如果解決了發佈的問題,請通過接受答案來解決問題。 –
(a:Seq [Int],b:Seq [Int])=>(a zip b).toMap提供了問題。我正在研究這個問題 由於數據類型不匹配,無法解析'UDF(col_1,col_2)':參數2需要數組類型,但'col_2'是數組類型。 ' 嘗試在udf中使用數字/小數。仍然沒有工作 –