2017-02-07 54 views
0

我有一個表查詢結果看起來像這樣(幾個SQL查詢後):組SQL結果由唯一的列,並添加其餘的列表,在一個獨特的羣體

Element Subelement ID   Email    Value 

1003022 10003981 "454255" "[email protected]" 25.5  
1003022 10003981 "454109" "[email protected]" 34.45  
1003027 10033987 "454369" "[email protected]" 1.9 
1003027 10033987 "454255" "[email protected]" 25.5  
1003011 10021233 "454209" "[email protected]" 34.45 
1222011 13513544 "454209" "[email protected]" 34.45 

這些都是一些事件與前兩列不同,作爲一個組。 col1處上校2

基於ID(電子郵件和價值是一個ID是相同的),我想有這樣的結果:

ID   Email    Value Elements 

"454255" "[email protected]" 25.5 {[1003022, 10003981], [1003027, 10033987]} 
"454109" "[email protected]" 34.45 {[1003022, 10003981], [1003011, 10021233], [1222011, 13513544]} 
"454369" "[email protected]" 1.9  {[1003027, 10033987]} 

或者說保持ID任何格式(電子郵件,值),並將元素和子元素添加到列表/數組中。

更新: 我試過group_concat,但找不到辦法做到這一點。

回答

1

這個怎麼樣?

#standardSQL 
SELECT ID, email, value, ARRAY_AGG(STRUCT(element, subelement)) AS Elements 
FROM YourTable 
GROUP BY ID, email, value; 
0

使用標準SQL,你可以做到以下幾點:

#standardSQL 
with t as 
(select 1003022 element, 10003981 subelement, "454255" id, "[email protected]" email, 25.5 value union all 
select 1003027, 10033987, "454255", "[email protected]", 25.5)  
SELECT id, email, value, 
     array_agg(struct<array<int64>>([element, subelement])) elements 
FROM t 
GROUP BY 1, 2, 3 
0
#standardSQL 
WITH yourTable AS (
    SELECT 1003022 AS Element, 10003981 AS Subelement, "454255" AS ID, "[email protected]" AS Email, 25.5 AS Value UNION ALL  
    SELECT 1003022 AS Element, 10003981 AS Subelement, "454209" AS ID, "[email protected]" AS Email, 34.45 AS Value UNION ALL  
    SELECT 1003027 AS Element, 10033987 AS Subelement, "454369" AS ID, "[email protected]" AS Email, 1.9 AS Value UNION ALL 
    SELECT 1003027 AS Element, 10033987 AS Subelement, "454255" AS ID, "[email protected]" AS Email, 25.5 AS Value UNION ALL  
    SELECT 1003011 AS Element, 10021233 AS Subelement, "454209" AS ID, "[email protected]" AS Email, 34.45 AS Value UNION ALL 
    SELECT 1222011 AS Element, 13513544 AS Subelement, "454209" AS ID, "[email protected]" AS Email, 34.45 AS Value 
)  
SELECT 
    ID, Email, Value, 
    CONCAT('{', STRING_AGG(CONCAT('[', CAST(Element AS STRING), ',', CAST(Subelement AS STRING), ']')), '}') AS Elements 
FROM yourTable 
GROUP BY ID, Email, Value 
-- ORDER BY Email 

結果是

ID  Email    Value Elements  
454255 [email protected] 25.5 {[1003022,10003981],[1003027,10033987]} 
454209 [email protected] 34.45 {[1003022,10003981],[1003011,10021233],[1222011,13513544]} 
454369 [email protected] 1.9  {[1003027,10033987]} 

你的問題在預期輸出的感覺有點模糊,因此你有很多答案
我認爲 - 越多越好:o)

相關問題