将两个选择表达式与左联接组合

时间:2019-08-22 05:55:47

标签: sql left-join teradata

嗨,我正在尝试为我的回归研究收集汇总的时间序列数据。我需要使用日期键在一个纵向表中左联接多个选择。但是,由于我正在处理相当大的数据框,因此需要限制查询的日期间隔。


SELECT ts.date_of_transaction,
           s.rev

    FROM db.transaction as ts
    --Where ts.date_of_transaction > date '2019-08-13'

LEFT JOIN 

(select date_of_transaction, sum(amount) as rev from db.transaction where  date_of_transaction >= date '2019-08-13' and
    main_group_number=200 and
    group_number=15 and
    class_number in (45,25,20,30)
    group by date_of_transaction) as s 

ON  ts.date_of_transaction = s.date_of_transaction; 

当我关闭第四行的where子句时,我的查询可以正常工作。但是,当我添加时间过滤器以查询外部表时,收到以下错误...

  

选择失败。 3706:语法错误:字符串或Unicode字符文字与'LEFT'关键字之间应有相似之处。

4 个答案:

答案 0 :(得分:2)

您不能在SELECT的WHERE子句中进行JOIN。请将WHERE放在最末端。

SELECT ts.date_of_transaction,
           s.rev

    FROM db.transaction as ts

LEFT JOIN 

(select date_of_transaction, sum(amount) as rev from db.transaction where  date_of_transaction >= date '2019-08-13' and
    main_group_number=200 and
    group_number=15 and
    class_number in (45,25,20,30)
    group by date_of_transaction) as s 

ON  ts.date_of_transaction = s.date_of_transaction

Where ts.date_of_transaction > date '2019-08-13'

答案 1 :(得分:0)

您在此部分中有错误。有很多方法可以将字符串值转换为日期格式。您可能会找到此链接以获得帮助。 link

select date_of_transaction, sum(amount) as rev from db.transaction where 
 date_of_transaction >= cast('2019-08-13' as date) and    ---- here instead of date You need to cast your string to date
    main_group_number=200 and
    group_number=15 and
    class_number in (45,25,20,30)
    group by date_of_transaction

答案 2 :(得分:0)

最简单的方法-

ts.date_of_transaction> '13 aug 2019'

答案 3 :(得分:0)

根据您的实际查询,您可能可以用 Windowed Aggregate Case 替换 Left Join (尤其是当您访问多次使用不同的条件或聚合级别的同一张表),例如

SELECT ts.date_of_transaction,
       sum(case when main_group_number=200
                 and group_number=15
                 and class_number in (45,25,20,30)
                then amount
            end)
       over (partition by date_of_transaction) as rev
FROM db.transaction as ts
Where ts.date_of_transaction > date '2019-08-13'
  

进行回归研究

Teradata具有一些内置的统计/回归功能,例如KURTOSISREGR_SLOPE,...