加入多个select sql语句(4个表)

时间:2016-12-21 13:42:01

标签: mysql

我需要将两个SQL语句连接在一起,这两个语句都可以自行运行。但我不知道如何将两者合并为一个SQL语句。

我在第一个陈述中有两个表,TR120TR1201

SQL是这样的:

select 
    PRODUCT, PRICE, QUANTITY, INVOICE.DATE 
from 
    TR1201
left join 
    (select 
         DATE, ID as INVOICE_ID, INVOICE 
     from TR120) as INVOICE on INVOICE.INVOICE_ID = ID 
where 
    INVOICE.DATE >= '2016-06-01' and INVOICE.DATE <= '2016-06-30'

这将返回我销售的所有产品的清单,其中包含价格,数量和销售日期,具体时间范围为01-06-16至06-06-16。

现在,我需要根据第一条SQL声明中的产品和销售日期,找出我在不同的两个表TR100TR1001中购买产品的最新价格。

select 
    PRODUCT, PRICE, SUP.DATE  
from 
    TR1001 
left join 
    (select 
         DATE, ID as SUP_ID, SUP_INVOICE 
     from TR100) as SUP on SUP.SUP_ID = ID

这将返回我已购买的所有产品的清单,其中包含价格和日期。根据产品和购买日期,我只需要此查询的最后一条记录。

TR120

ID | INVOICE | DATE
1  | 000001  |2016-06-05
2  | 000002  |2016-06-15
3  | 000003  |2016-06-25

TR1201

ID | PRODUCT | PRICE A | QUANTITY
1  | A       | 2,00    |    5
2  | A       | 2,00    |    2
3  | A       | 2,00    |    1

TR100

ID | SUP_INVOICE | DATE
1  | 160001      | 2016-05-30
2  | 160002      | 2016-06-16

TR1001

ID | PRODUCT | PRICE B
1  | A       | 0,5
2  | A       | 0,7

我想要得到的结果是:

PRODUCT | PRICE A (tr1201) | QUANTITY | DATE (tr100) | PRICE B (tr1001)
A       | 2                |  5       | 2016-05-30   |   0,5
A       | 2                |  2       | 2016-05-15   |   0,5
A       | 2                |  1       | 2016-05-16   |   0,7

这就是我想做的一切:(

2 个答案:

答案 0 :(得分:0)

你试过first_value吗?

  select distinct id, 
         first_value(price) over (partition by id (,sup) order by date DESC (latest, ASC for oldest)) as last_price
 from table;

它的工作原理如下:

$array = [1,2,3,4,5,6,7]; //or $array = [1,2,3,4,5,6,7,8]

public function getNumberNotReversed($array, $number) {
    return $array[$number - 1];
}

public function getNumberReversed($array, $number) {
    return array_reverse($array)[$number - 1];
}

echo getNumberNotReversed($array, 2); //print 2 (base 7 or 8)
echo PHP_EOL;
echo getNumberReversed($array, 2); //print 6 (base 7), print 7 (base 8)

可以在此处找到文档:https://msdn.microsoft.com/en-us/library/hh213018.aspx

答案 1 :(得分:0)

我没有你的桌子因此无法测试,因此我只提供建议。 我认为你需要的是像这样的外部应用而不是连接

select 
      T1.Product
    , T1.Price
    , T2.DATE   -- Alias this
    , T2.Price  -- Alias this
    , T3.DATE   -- Alias this
    , T3.Price  -- Alias this
from T1
OUTER APPLY (
    select top 1
          Date
         ,Price
    from table2
    WHERE ID = T1.Id AND product = T1.Product-- plus any other joins
    ORDER BY Date desc
) as T2 
OUTER APPLY (
    select top 1 
          Date
         ,Price
    from table3
    WHERE ID = T1.Id AND product = T1.Product-- plus any other joins
    ORDER BY Date desc
) as T3