2017-08-01 59 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正被用作虚拟列来按日历日期对数据进行分组 –