2或3个表上的Mysql查询

时间:2016-12-01 16:05:59

标签: mysql

|              ds               |   
|sales_id|    date_issued       |
|    1   |  2016-11-30 01:00:00 |
|    2   |  2016-11-30 02:00:00 |
|    3   |  2016-11-30 03:00:00 |

|             dsr                         |
|  dsr_id | quantity |   date_returned    |
|    5    |    1     | 2016-11-30 01:01:00|
|    6    |    1     | 2016-11-30 01:11:00|
|    7    |    3     | 2016-11-30 02:21:00|
|    8    |    1     | 2016-11-30 02:31:00|
|    9    |    2     | 2016-11-30 03:02:00|

我可以应用此逻辑的方式或内容是什么 添加dsr WHERE的数量,其date_returned大于第一个date_issued AND小于以下date_issued 结果将是:

|    2    |
|    4    |  
|    2    |   

这个想法是这样的:

|             dsr                         |
|  dsr_id | quantity |   date_returned    |
|    5    |    1     | 2016-11-30 01:01:00| --- This 1st and 2nd rows
|    6    |    1     | 2016-11-30 01:11:00| --/ will be added because
                                             the 1st date_issued is 
'2016-11-30 01:00:00' >= (the 1st date_returned) < '2016-11-30 02:00:00' which is the following date_issued

|    7    |    3     | 2016-11-30 02:21:00| --- Same idea for this two
|    8    |    1     | 2016-11-30 02:31:00| --/ Since its fits to the condition where this date_returned is just between 2nd & 3rd's date_issued

|    9    |    2     | 2016-11-30 03:02:00|

我知道这可以通过编程方式轻松完成,但我只想知道并学习如何在SQL中执行此操作,以及在SQL中是否更容易。

1 个答案:

答案 0 :(得分:0)

<强> SQL DEMO

SELECT start_date, end_date, SUM(D.quantity)
FROM (
        SELECT ds1.`sales_id`, 
               ds1.`date_issued` start_date,  
               COALESCE(ds2.`date_issued`, CURRENT_DATE) as end_date
        FROM ds as ds1
        LEFT JOIN ds as ds2
          ON ds1.`sales_id` = ds2.`sales_id` - 1
     ) R
JOIN dsr D
  ON D.`date_returned` >= start_date
 AND D.`date_returned` <  end_date
GROUP BY  start_date, end_date

<强>输出

enter image description here