将来自多个表的数据与特定数据语句组合在一起

时间:2013-11-28 17:18:28

标签: sql join teradata database-table

使用Tereadata需要一些帮助我需要提取一个连接许多表的报告......这是基本概念:

Select Table1.ID, Table2.Arrival_date, Table2.Name
From Table1
     Inner Join Table1.ID on Table2.ID
Where table2.arrival_date between '10/01/2013' and '10/02/2013'

然后还有另一个包含以下信息的表

ID     Item     Cost     Date
1      Flour    1.99     10/02/2013
2      cheese   3.99     10/01/2013
3      Flour    1.99     8/16/2013

我想将其添加到上面的表格中

Select Itemtable.ID, Itemtable.item, itemtable.cost, itemtable.date
from itemtable
where itemtable.date between '10/01/2013' and 10/02/2013
and itemtable.item like '%flour%'

Itemtable.ID = Table1.ID - 但是当我加入时,我只得到那些购买面粉的顾客 - 我希望在该日期框架之间看到所有顾客,如果他们买面粉需要它 - 我的最终餐桌会看起来像这样:

ID    Arrival Date    Name     ID     Item     Cost     Date
1     10/01/2013       Dan
2     10/01/2013       Mike
3     10/01/2013       Nancy
1     10/02/2013       Dan      1      Flour   1.99     10/02/2013
5     10/02/2013       Mary   

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

大致输入(我没有实际的表定义所以我必须动态地进行此操作),但基本上你想先过滤销售,然后从客户那里执行左连接;类似......

select Table2.ID, Table2.Arrival_dime, Table2.Name
from Table2
  left join (
    select Itemtable.ID, Itemtable.item, Itemtable.cost, ItemTable.date
    where where itemtable.date between '10/01/2013' and 10/02/2013
    and itemtable.item like '%flour%') itemTable on Table2.ID = itemTable.ID
where table2.arrival_date between '10/01/2013' and '10/02/2013'