SQL - 在另一个SELECT的WHERE子句中使用SELECT

时间:2016-10-24 10:14:30

标签: sql select

我有下一个查询

select No, 
       Description, 
       Item,
       Date
from myTable1

并获取

enter image description here

只有一个选择

select * from myTable2

并获取

enter image description here

现在我需要从MyTable1中选择所有数据并加入MyTable2

获取数量

的总和

分组 ITEM

其中MyTable2.Date< = MyTable1.Date

有什么想法吗?

我想得到这张表

enter image description here

5 个答案:

答案 0 :(得分:1)

试着这个让你开始,没有更多的信息很难得到准确的答案:

SELECT T1.No
     , T1.Item
     , SUM(T2.Quantity)
     , MIN(T1.Date) as Date FROM mytable1 T1
  INNER JOIN mytable2 T2 
       ON T1.No = T2.No AND T1.Item = T2.Item AND T2.Date <= T1.Date
  GROUP BY T1.No, T1.Item

答案 1 :(得分:1)

试试这个:

select t1.*,sum(t2.quantity)
from myTable1 t1
INNER JOIN mytable2 t2 on t2.no = t1.no and t2.item=t1.item
WHERE t2.date<=t1.date
GROUP BY t1.No,t1.item

答案 2 :(得分:1)

试试这个。

            SELECT 
            T1.No,
            t1.Description , 
            T1.Item, 
            MIN(T1.Date) as Date ,
            SUM(T2.Quantity) as Quantity
            FROM Table1 T1 INNER JOIN Table2 T2 
            ON T1.No = T2.No AND T1.Item = T2.Item AND T2.Date <= T1.Date
            GROUP BY T1.No, T1.Item , T1.Description

如果您有任何问题,请告诉我们。

答案 3 :(得分:0)

SELECT No,Description,Item,Date,sum(t2.quantity) 来自myTable1 在myTable1.No = myTable2.No和Description =项目上加入myTable2 在哪里MyTable2.Date&lt; = MyTable1.Date GROUP BY否,描述,项目,日期

答案 4 :(得分:0)

试试这个:

            select * from
            (
            SELECT ID,CLASS, CHANGE_NUMBER AS OBJECT_NUMBER FROM table_A
            UNION
            SELECT ID,CLASS,CUST_NO AS OBJECT_NUMBER FROM table_B
            ORDER BY ID
            ) x where x.id ='5434';