2017-08-01 89 views
0

我想從兩個不同的表中提取數據以獲得以下內容 - 請參閱附加圖像The data that I am after。我的目標是讓存款人的數量獨立於每天活躍的玩家。也就是說,如果玩家存款但沒有玩,我仍然希望玩家被計數。將兩個PostgreSQL表中的數據合併爲一個

我正在使用下面的代碼,但結果不是我以後的 - 看圖像The data that I am getting。我只在每個國家/地區每行獲得一個calendar_date(2017-01-01)。這兩個日期的數據總結爲一個&還有另一行數據(在存儲器& Total_Deposit_Amount下),它不屬於任何國家。這些數據應該分佈在各個國家之間。

--temporary table for start_date 
WITH Temp_Start_Date as 
(
select CAST('2017-01-01' AS date) 
), 

--temporary table for end_date 

Temp_End_Date as 
(
select CAST('2017-01-03' AS Date) 
), 

--temporary table for calendar date 
Temp_Calendar_Date as 
(
    SELECT 1 as LinkDate 
     ,calendar_date::date from generate_series('2017-01-01', 
      CURRENT_DATE -212, '1 day'::interval) calendar_date 

), 

--temporary table for bet_transactions 
Temp_bet_transactions AS 
(
     SELECT BT.account_id 
     , P.username 
     , CASE 
      WHEN P.country_code = '1' then '1' 
      WHEN P.country_code = '2' then '2' 
      WHEN P.country_code = '3' then '3' 
      WHEN P.country_code = '4' then '4' 
      WHEN P.country_code = '5' then '5' 
      WHEN P.country_code = '6' then '6' 
      ELSE '7' 
     END AS Country 
     , 1 AS LinkDate 
     , SUM(CAST(CAST(money_amount_cents AS DECIMAL (18,2))/100 AS DECIMAL (18,2))) AS Turnover 
    FROM accounts A 
    JOIN players P ON A.player_id = P.id 
    JOIN ONLY bet_transactions BT ON A.id = BT.account_id 
    WHERE BT.created_at >= (SELECT * FROM Temp_Start_Date) 
     AND BT.created_at < (SELECT * FROM Temp_End_Date) 
     AND BT.status = 'accepted' 
     AND amount_cents <> 0 
    GROUP BY 
     1, 2, 3 
), 

--temporary table for depositors 
Temp_depositors AS 
(
    SELECT account_id 
     , 1 AS LinkDate 
     , SUM(CAST(CAST(money_amount_cents AS DECIMAL (18,2))/100 AS DECIMAL (18,2))) AS Total_Deposit_Amount 
    FROM deposit_transactions D 
    WHERE D.created_at >= (SELECT * FROM Temp_Start_Date) 
      AND D.created_at < (SELECT * FROM Temp_End_Date) 
      AND status = 'accepted' 
    GROUP BY 
     1, 2 
) 

--get result 
SELECT TCD.calendar_date 
    , BT.country 
    , COUNT(DISTINCT BT.account_id) AS Active_Players 
    , COUNT(DISTINCT DT.account_id) AS Depositors 
    , SUM(DT.Total_Deposit_Amount) AS Total_Deposit_Amount 
    , SUM(BT.Money_Bet) AS Turnover 
FROM Temp_Calendar_Date TCD 
JOIN Temp_bet_transactions BT ON TCD.LinkDate = BT.LinkDate 
FULL OUTER JOIN Temp_depositors DT ON BT.account_id = DT.account_id 
GROUP BY 
    1,2 

任何幫助將不勝感激。

感謝 斯特凡

回答

0

我低信譽發表意見,所以我必須要問在這裏。

這通常是因爲Temp_Calendar_Date包含只有一行(與2017-01-01),你在這之後分組。

如果您提供一些插入來生成測試數據,那將會容易得多。

順便說一下,什麼是LinkDate? Wy這總是等於1

+0

Linkdate正被用作虛擬列來按日曆日期對數據進行分組 –