2017-10-17 111 views
-1

我被困在一個點上,我必須從客戶表中選擇具有customer_id和amount_paid值的數據。我想在表單中顯示一個結果,即用戶的前三個值應該在列名稱組中顯示爲文本Group1和該用戶的4到10個值以獲取文本Group2和其餘組Group3。在表上彙總查詢?

你能告訴我如何爲每個客戶分組值嗎?

感謝

回答

2

我想表明的形式的結果是用戶的第一3個值應在列名組爲文本Group1和用戶的4至10個值來獲得文本可見第2組和第3組休息

下面是BigQuery的標準SQL

#standardSQL 
SELECT 
    user_id, 
    CASE 
    WHEN pos BETWEEN 1 AND 3 THEN 1 
    WHEN pos BETWEEN 4 AND 10 THEN 2 
    ELSE 3 
    END grp, 
    SUM(amount_paid) amount_paid 
FROM (
    SELECT 
    user_id, amount_paid, 
    ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY amount_paid DESC) pos 
    FROM customer 
) 
GROUP BY user_id, grp 
-- ORDER BY user_id, grp 

您可以T EST /下面的虛擬再現而生成的數據

#standardSQL 
WITH users AS (
    SELECT user_id FROM UNNEST(GENERATE_ARRAY(1,5)) user_id 
), 
amounts AS (
    SELECT ROUND(50 * RAND()) amount_paid FROM UNNEST(GENERATE_ARRAY(1,50)) amount_paid 
), 
customer AS (
    SELECT user_id, ROUND(amount_paid * RAND()) amount_paid 
    FROM users 
    CROSS JOIN amounts 
) 
SELECT 
    user_id, 
    CASE 
    WHEN pos BETWEEN 1 AND 3 THEN 1 
    WHEN pos BETWEEN 4 AND 10 THEN 2 
    ELSE 3 
    END grp, 
    SUM(amount_paid) amount_paid 
FROM (
    SELECT 
    user_id, amount_paid, 
    ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY amount_paid DESC) pos 
    FROM customer 
) 
GROUP BY user_id, grp 
ORDER BY user_id, grp 

輸出將類似於下面

user_id grp amount_paid 
1  1 147.0  
1  2 323.0  
1  3 879.0  
2  1 147.0  
2  2 323.0  
2  3 879.0  
. . .  

所以你仍然需要計算其(從你的問題,並希望)共享是不是一個問題,你

加入份額計算

#standardSQL 
WITH grps AS (
    SELECT 
    user_id, 
    CASE 
     WHEN pos BETWEEN 1 AND 3 THEN 1 
     WHEN pos BETWEEN 4 AND 10 THEN 2 
     ELSE 3 
    END grp, 
    SUM(amount_paid) amount_paid 
    FROM (
    SELECT 
     user_id, amount_paid, 
     ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY amount_paid DESC) pos 
    FROM customer 
) 
    GROUP BY user_id, grp 
) 
SELECT * , 
    ROUND(amount_paid/SUM(amount_paid) OVER(PARTITION BY user_id), 3) share 
FROM grps 
-- ORDER BY user_id, grp 
+0

非常感謝米哈伊爾:) – Mahesh

+0

嵌套查詢會很好 - 我沒有看到在一次運行中的所有必要性。這當然是性感的,但更多的錯誤和難以維護。感覺良好的嵌套查詢 - 只是試着讓我們知道如果仍然需要幫助,將需要:0) –

+0

嗨米哈伊爾,我試過了,但我沒有得到成功。你會指導我如何解決這個問題? – Mahesh