簡體   English   中英

如何根據另一個表中的兩個日期字段獲取一個表中的記錄數

[英]how to get the count of records in one table based on two date fields in another table

如何根據另一個表中的兩個日期字段獲取一個表中的記錄數

例如:
表1:葉子

| leav_id     | from      | to             |


| 1           | 2015-10-20 | 2015-10-27    |

| 2           | 2015-11-10 | 2015-10-12    |

表2:假期

| holi_id     | On         | Name       |


| 1           | 2015-12-25 | Christmas  |

我想得到number days between from and to in table leaves excluding the count of holidays from table holiday in that rangenumber days between from and to in table leaves excluding the count of holidays from table holiday in that range

這是你可以做的,我已經為計算創造了一些假期

mysql> select * from leaves ;
+---------+------------+------------+
| leav_id | from       | to         |
+---------+------------+------------+
|       1 | 2015-10-20 | 2015-10-27 |
|       2 | 2015-12-20 | 2015-12-30 |
+---------+------------+------------+
2 rows in set (0.00 sec)

mysql> select * from holidays ;
+---------+------------+----------+
| holi_id | on         | name     |
+---------+------------+----------+
|       1 | 2015-12-25 | X-Mass   |
|       2 | 2015-12-26 | Saturday |
|       3 | 2015-12-26 | Sunday   |
|       4 | 2015-10-24 | Saturday |
|       5 | 2015-10-25 | Sunday   |
+---------+------------+----------+

因此,以下查詢將為您提供不包括假期的總葉數

select 
t1.leav_id,
( 
  datediff(t1.`to`,t1.`from`) 
  - 
  sum(
    case when t2.`on` >= t1.`from` and t2.`on` <= t1.`to` 
    then 1 else 0  end
  ) 
) as total_leave
from  leaves t1 
left join holidays t2 on t2.`on` >= t1.`from` 
and t2.`on` <= t1.`to` 
group by t1.leav_id 

結果將是

+---------+-------------+
| leav_id | total_leave |
+---------+-------------+
|       1 |           5 |
|       2 |           7 |
+---------+-------------+

另請注意, datediff函數可能無法給出正確的結果,例如

mysql> select datediff('2015-12-30','2015-12-20') as d ;
+------+
| d    |
+------+
|   10 |
+------+

這是它的10天,但是當假期計算為11時,即從2015-12-202015-12-30

因此需要重新考慮上面的查詢以添加+1作為

select 
t1.leav_id,
( 
  datediff(t1.`to`,t1.`from`) 
  - 
  sum(
    case when t2.`on` >= t1.`from` and t2.`on` <= t1.`to` 
    then 1 else 0 end
   ) 
 )+1 as total_leave
from  leaves t1 
left join holidays t2 on t2.`on` >= t1.`from` 
and t2.`on` <= t1.`to` 
group by t1.leav_id 

並且會給予

+---------+-------------+
| leav_id | total_leave |
+---------+-------------+
|       1 |           6 |
|       2 |           8 |
+---------+-------------+

首先使用datediff : -

select datediff(to, from) as day from leaves

我已經編輯了我的答案,請你試試這個。

SELECT l.*, 
datediff(l.`to`, l.`from`) as leavedays,
IF((SELECT h.holiday FROM holidays AS h WHERE h.holiday between l.`from` AND l.`to`)<>'',1,0) AS holyday,
(datediff(l.`to`, l.`from`)-(SELECT IF(count(h.holiday)='',0,count(h.holiday)) FROM holidays AS h WHERE h.holiday between l.`from` AND l.`to`) AS totalday
FROM
leaves AS l

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM