SQL - 无法获取JOIN做我想要的

时间:2014-06-24 14:57:37

标签: sql join

我有三张桌子:
tab1具有客户ID,开始日期和结束日期
tab2具有类型1的交易数据:客户ID,交易日期,交易金额
tab3具有类型2交易数据:客户ID,交易日期,交易金额

我想要一张包含以下列的表格:
col1:player_ID
col2:来自tab1(类型1交易)的交易金额之和在tab1的相关开始日期和结束日期之间发生 col3:来自tab1的相关开始日期和结束日期之间发生的tab3(类型2交易)的交易金额总和

如果我通过加入玩家ID上的两个表并使用:

加入tab1和tab2,我就可以了
sum(case when (transaction date >= start date AND transaction date <= end date) then transaction amount else 0 end)

但是当我在播放器ID上加入tab3时,前一个总和给了我不同的和更高(和错误)的值。我确定我在创作的笛卡尔产品上犯了错误,但是

我没有加入tab3,而是尝试使用tab3上的子查询,但我的netezza sql不允许我这样做...

我不知道如何解决它......

**评论后更新***

这是我试图运行的查询:

SELECT lm.player_id,
/*SALES BEFORE limit starts */
sum(case when (dt.cal_day_dt<=lm.hit_time and dt.cal_day_dt>lm.hit_time-14) then  .sales_amount else 0 end) as sales_before14,

/*SALES BEFORE limit starts - Control group */
(select sum(amount_won) from IA_PLAYER_WINNERS where transaction_time<=lm.hit_time and transaction_time>lm.hit_time-14) as sales_before14_control
from (  
select player_id, min(hit_time) as hit_time, re_enable_date, limits
from IA_PLAYER_SPENDING_LIMITS
where limit_type='W'
group by player_id, re_enable_date, limits
) lm
join IA_PLAYER_SALES_HOURLY s ON lm.player_id = s.player_id
join IA_DATES dt ON s.date_key = dt.date_key
join IA_PRODUCTS pr ON s.product_key = pr.product_key
where lm.hit_time >='2014-03-25' and lm.re_enable_date<='2014-05-24'
group by lm.player_id, lm.re_enable_date, lm.limits
order by lm.player_id;

我收到此错误:&#34;关系&#39; LM&#39;不存在&#34;

当我试图消除对LM的引用时,我遇到了这个新错误:  &#34; Sub-SELECT使用un-GROUPed属性&#34; RSS &#34;。#HIT_TIME#0xa69fca4来自外部查询&#34;

3 个答案:

答案 0 :(得分:0)

您需要两个完全独立的查询,其结构非常相似,一个用于tab2,一个用于tab3(或两个子查询,或两个或三个视图,具体取决于您的SQL方言允许的内容),因为您的tab2和tab3完全不相关;你不能以任何明智的方式加入他们。

您的测试中可能会发生的情况是,三个表的连接在tab2中为具有相同customer_id的tab3中的每一行重复行,反之亦然,总结每个事务的多个副本。

答案 1 :(得分:0)

SELECT tab1.ID,
       (SELECT SUM(tab2.amount) FROM tab2 WHERE tab2.id=tab1.id AND tab2.startdate<=tab1.transdate AND tab1.transdate<=tab2.enddate),
       (SELECT SUM(tab3.amount) FROM tab3 WHERE tab3.id=tab1.id AND tab3.startdate<=tab1.transdate AND tab1.transdate<=tab3.enddate)
FROM tab1

答案 2 :(得分:0)

尝试这个SQL兄弟,希望它能运作

SELECT
  A.customer_id,
  (SELECT
     SUM(B.transaction_amount)
   FROM tab2 B
   WHERE B.customer_id = A.customer_id
       AND B.transaction_date >= A.start_date
       AND B.transaction_date <= A.end_date
   GROUP BY B.customer_id) AS TAB2_amount,
  (SELECT
     SUM(C.transaction_amount)
   FROM tab3 C
   WHERE C.customer_id = A.customer_id
       AND C.transaction_date >= A.start_date
       AND C.transaction_date <= A.end_date
   GROUP BY C.customer_id) AS TAB3_amount
FROM tab1 A
ORDER BY 1